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 does not have constructors
-尽管在我看来,除了语法外,没有任何改变.我是否误解了接口在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中定义的接口,目前不支持.相反,您需要定义一个实现该接口的匿名对象:
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屋!