android - 覆盖 Kotlin lambda 表达式中的多个接口(interface)方法

标签 android lambda interface kotlin

假设我有一个 Callbacks 接口(interface),它有两个方法 onCurrentLocationonError:

    public interface Callbacks {

        void onCurrentLocation(ClientLocation location);

        void onError();
    }

和一个在其构造函数中采用此接口(interface)的类,例如:

public MyLocationClient(Callbacks callbacks) {...}

现在,在 Kotlin 中,我是否应该能够以这种方式实例化 MyLocationClient:

val myLocationClient = MyLocationClient(
                    { location: ClientLocation ->
                          updateClientLocation(location)
                    },
                    {})

如果不是,为什么不呢?

我看到的行为是:当接口(interface)只有一个方法时,这个对象的构造编译得很好。但是,只要我向 Callbacks 添加更多方法,编译器就会提示

"Type mismatch. Required: Callbacks! Found: (ClientLocation) -> Unit"

编辑:删除了对 location 的空检查,因为它与问题无关。

最佳答案

所以你在一个不是功能接口(interface)的匿名类上创建一个实例(它们只有一个方法)所以它会是这样的:

val myLocationClient = MyLocationClient(object : Callbacks {

        override fun onCurrentLocation(location : ClientLocation?){
            location?.run{ updateLocation(this) }
        }

        override fun onError(){ // should you not handle errors? }
    })

关于android - 覆盖 Kotlin lambda 表达式中的多个接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46534885/

相关文章:

java - 程序排除除 1,2,3 之外的数字

java - 对于其他非模块化项目,如何使 Java 类在其模块之外不可见?

java - 抽象类实现接口(interface)

android - phonegap应用中assets/www文件和src/*.java文件的关系

android - Kotlin 将 getter 用于只读变量

c# - 动态生成调用 Lambda 函数的按钮——变量作用域

c# - lambda 表达式中的 .Sum()

c# - 如何实现定义另一个接口(interface)元素的接口(interface)

android - MPAndroidChart - 在 MarkerView 中单击按钮

Android KitKat 获取 Toast 半径?