我有一个委托(delegate)接口(interface):
interface Delegate {
fun didSelectWord(word: String)
}
我想要一个名为delegate
的属性
val delegate: <T> where T : Delegate
delegate
可以是任何实现 Delegate 的东西
我也尝试过
val delegate: Any : Delegate
但是都给出编译错误
最佳答案
解决办法很简单
val delegate: Delegate
现在这样的事情就可以了
interface Delegate
class Test: Delegate {
fun yourMethod() = "Your Method"
}
fun test() {
val delegate: Delegate
delegate = Test()
println(delegate)
}
如果您想使用仅存在于 Test
中但不存在于 Delegate
中的函数,则必须对其进行强制转换
(delegate as Test).yourMethod()
否则,只有 Delegate
中存在的函数才有效
delegate.yourMethod()
将不起作用。
关于 Kotlin "Any type that implements an interface",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45774365/