2

拡張機能にいくつかのレシーバーが必要です。たとえば、関数でとインスタンスhandleの両方のメソッドを呼び出せるようにします。CoroutineScopeIterable

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

パラメータで関数を作成できることは知っていますが、

単一の機能に対して複数のレシーバーを使用することは可能ですか?パラメーターなしでそれを行う方法は?

4

2 に答える 2

1

これは非常に狭いケースですが、ラムダのコードに複数のレシーバーを持たせたい高次関数があるユースケースであり、結合したい型がインターフェイスである場合は、クラスを作成できますインターフェイスをデリゲートとしてラップします。以下の関数に渡されるラムダ内で、Iterable 関数と CoroutineScope 関数の両方を呼び出すことができます。

class CoroutineScopeAndIterable<T>(
    private val coroutineScope: CoroutineScope,
    private val iterable: Iterable<T>
): CoroutineScope by coroutineScope, Iterable<T> by iterable

suspend fun <T> CoroutineScope.runSomething(
    iterable: Iterable<T>, 
    block: suspend CoroutineScopeAndIterable<T>.() -> Unit
) {
    CoroutineScopeAndIterable(this, iterable).block()
}
于 2022-01-17T17:44:28.770 に答える