我希望我的扩展功能有几个接收器。例如,我想要函数 handle
能够调用两个CoroutineScope
的方法和 Iterable
实例:
fun handle() {
// I want to call CoroutineScope.launch() and Iterable.map() functions here
map {
launch { /* ... */ }
}
}
我认为这可能有效:fun <T> (Iterable<T>, CoroutineScope).handle() {}
但这给了我一个错误:Function declaration must have a name
我知道我可以创建带有参数的函数,但是单个函数是否可以有多个接收器,以及如何在没有参数的情况下做到这一点?
最佳答案
在 Kotlin 版本中 1.6.20 有一个名为 的新功能Context receivers .这是上下文接收器的第一个原型(prototype)。此功能允许通过将上下文接收器添加到其声明中来使函数、属性和类与上下文相关。有一种新的语法。在函数声明之前,我们可以指定调用此函数所需的上下文类型列表。上下文声明执行以下操作:
带有上下文接收器的解决方案如下所示:
context(CoroutineScope)
fun <T> Iterable<T>.handle() {
map {
launch { /* ... */ }
}
}
someCoroutineScope.launch {
val students = listOf(...)
students.handle()
}
在 context(CoroutineScope)
我们可以声明多种类型,例如 context(CoroutineScope, LogInterface)
.由于上下文接收器功能是一个原型(prototype),要启用它添加
-Xcontext-receivers
应用程序的 build.gradle
中的编译器选项文件:apply plugin: 'kotlin-android'
android {
//...
kotlinOptions {
jvmTarget = "11"
freeCompilerArgs += [
"-Xcontext-receivers"
]
}
}
关于android - 如何在 Kotlin 中创建具有多个接收器的扩展函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70739459/