Kotlin:接口......没有构造函数 [英] Kotlin: Interface ... does not have constructors
问题描述
我正在将一些 Java 代码转换为 Kotlin,但我不太明白如何实例化在 Kotlin 代码中定义的接口.例如,我有一个接口(在 Java 代码中定义):
I am converting some of my Java code to Kotlin and I do not quite understand how to instantiate interfaces that are defined in Kotlin code. As an example, I have an interface (defined in Java code):
public interface MyInterface {
void onLocationMeasured(Location location);
}
然后在我的 Kotlin 代码中进一步实例化这个接口:
And then further in my Kotlin code I instantiate this interface:
val myObj = new MyInterface { Log.d("...", "...") }
而且它工作正常.但是,当我将 MyInterface 转换为 Kotlin 时:
and it works fine. However, when I convert MyInterface to Kotlin:
interface MyInterface {
fun onLocationMeasured(location: Location)
}
我收到一条错误消息:当我尝试实例化它时,Interface MyListener 没有构造函数
- 尽管在我看来,除了语法之外没有任何变化.我是否误解了接口在 Kotlin 中的工作原理?
I get an error message: Interface MyListener does not have constructors
when I try to instantiate it - though it seems to me that nothing has changed except syntax. Do I misunderstand how interfaces work in Kotlin?
推荐答案
您的 Java 代码依赖于 SAM 转换 - 将 lambda 自动转换为具有单个抽象方法的接口.Kotlin 中定义的接口目前不支持 SAM 转换.相反,您需要定义一个实现该接口的匿名对象:
Your Java code relies on SAM conversion - an automatic conversion of a lambda into an interface with a single abstract method. SAM conversion is currently not supported for interfaces defined in Kotlin. Instead, you need to define an anonymous object implementing the interface:
val obj = object : MyInterface {
override fun onLocationMeasured(location: Location) { ... }
}
这篇关于Kotlin:接口......没有构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!