android - 如何在 Kotlin 中创建具有多个接收器的扩展函数?

标签 android kotlin kotlin-coroutines extension-function kotlin-context-receivers

我希望我的扩展功能有几个接收器。例如,我想要函数 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/

    相关文章:

    android - 外部播放器 : Custom AudioProcessor - Equalizer

    android - kotlin 中的通用 grpc 请求

    asynchronous - Kotlin:将 "normal"函数转换为阻塞挂起函数对性能有何影响?

    android - 录制视频时设置 durationLimit 或 sizeLimit 的替代方法?

    android - 回收站 View : animation restart when scroll up or down

    android - getDrawable 返回 null

    java - 为什么读取功能会自动将4k图像转换为1080p?

    android - 等待协程结果而不阻塞主线程

    android - 如何避免 android 子组件中的重复 id?

    java - 如何查看我何时将联系人添加到手机(android)