Generics SAM与泛型的转换

Generics SAM与泛型的转换,generics,kotlin,interface,Generics,Kotlin,Interface,我的接口定义如下: interface OnItemClickDelegate<T: Entity> { fun onItemClick(entity: T?) } 如何用简短的表示法编写声明?遗憾的是,Kotlin不支持Kotlin接口的这种开箱即用的语法,只支持java语法(无论是否使用泛型) 您可以做的是: interface OnItemClickDelegate<T : Entity> { fun onItemClick(entity: T?

我的接口定义如下:

interface OnItemClickDelegate<T: Entity> {
    fun onItemClick(entity: T?)
}

如何用简短的表示法编写声明?

遗憾的是,Kotlin不支持Kotlin接口的这种开箱即用的语法,只支持java语法(无论是否使用泛型)

您可以做的是:


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)
            }
    }
}

mclick委托接口{
有趣的McClick(实体:T?)
伴星{
内联操作符调用(交叉内联操作:(实体:T?->Unit)=
对象:代理{
重写mclick(实体:T?)=op(实体)
}
}
}
通过这种方式,您可以像下面这样实例化侦听器:

  val delegate = OnItemClickDelegate<Entity> {
                    //todo -> insert your callback code here
            }
val delegate=nominicclickdelegate{
//todo->在此处插入回调代码
}

从Kotlin 1.4开始,只需在接口声明之前添加
fun
,您就可以开始了,如下所示:

fun interface OnItemClickDelegate<T : Entity> {
    fun onItemClick(entity: T?)
}
fun接口和代理{
有趣的McClick(实体:T?)
}


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)
            }
    }
}
  val delegate = OnItemClickDelegate<Entity> {
                    //todo -> insert your callback code here
            }
fun interface OnItemClickDelegate<T : Entity> {
    fun onItemClick(entity: T?)
}