Kotlin "Any type that implements an interface"

标签 kotlin

我有一个委托(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/

相关文章:

kotlin - 具有共享模块的多平台项目

android - 在 Kotlin 中调用 String 方法当 block

android - 在 Kotlin 中创建非绑定(bind)服务

android - 代码在 lambda 表达式之外工作,但不能在内部工作

Kotlin:必须初始化变量 'result'

java - Gradle android找不到符号上下文

java - Kotlin Kmongo 插入并返回插入的项目

Android Kotlin Gson 慢速Json反序列化

android - RxJava2 定时器和 combineLatest

ios - 链接 iOS 框架时无法在 Kotlin Multiplatform 中运行 "linkDebugFrameworkIos"