我的接口定义如下:
interface OnItemClickDelegate<T: Entity> {
fun onItemClick(entity: T?)
}
现在,我在另一个类中匿名定义了接口:
var itemClickDelegate = object : OnItemClickDelegate<Derived> {
override fun onItemClick(entity: Derived?) {
doSomethingWith(entity)
}
}
这可以很好地编译,但是当我切换到:
var itemClickDelegate = OnItemClickDelegate<Derived> { entity -> doSomethingWith(entity) }
我收到一个编译器错误,提示:
Interface OnItemClickDelegate does not have constructors
如何用简短的注释写我的声明?
答案 0 :(得分:4)
可悲的是,对于Kotlin接口,Kotlin不支持该语法,仅支持Java(无论是否使用泛型)。
您可以执行以下操作:
[
{
"mca_sub1":1.1,
"mca_sub2":2.8,
"bca_sub1":1.1,
"bca_sub2":2.8
},
{
"mca_sub1":1.15,
"mca_sub2":1.18,
"bca_sub1":1.15,
"bca_sub2":1.18
},
{
"mca_sub1":1.2,
"mca_sub2":1.9,
"bca_sub1":1.2,
"bca_sub2":1.9
}
]
这样,您可以像这样实例化侦听器:
interface OnItemClickDelegate<T : Entity> {
fun onItemClick(entity: T?)
companion object {
inline operator fun <T : Entity> invoke(crossinline op: (entity: T?) -> Unit) =
object : OnItemClickDelegate<T> {
override fun onItemClick(entity: T?) = op(entity)
}
}
}
答案 1 :(得分:0)
从 Kotlin 1.4 开始,只需在接口声明前添加 fun
即可,如下所示:
fun interface OnItemClickDelegate<T : Entity> {
fun onItemClick(entity: T?)
}
https://kotlinlang.org/docs/whatsnew14.html#sam-conversions-for-kotlin-interfaces