查看kotlinx.coroutines中的這段代碼,我注意到一些奇怪的事情:
/**
* Returns a flow containing the results of applying the given [transform] function to each value of the original flow.
*/
public inline fun <T, R> Flow<T>.map(crossinline transform: suspend (value: T) -> R): Flow<R> = transform { value ->
return@transform emit(transform(value))
}
在第一行中,transform使用的是明確的this.transform(定義here)。不應該使用transform在方法引數中宣告的,因為它在第二行中?
為了測驗這一點,我寫了一個小類,試圖模仿這種行為:
// flow.kt
class Flow(val name: String) {
public fun transform (transform: (Any) -> Unit): Flow {
return Flow("transformed")
}
public fun emit(value: Any) {
// do nothing
}
public fun map(transform: (Any) -> Unit): Flow = transform { value ->
return@transform(emit(transform(value)))
}
}
當我運行時,我得到了我期望的那種警告kotlinc flow.kt:
flow.kt:12:54: error: type mismatch: inferred type is Unit but Flow was expected
public fun map(transform: (Any) -> Unit): Flow = transform { value ->
^
flow.kt:12:66: error: cannot infer a type for this parameter. Please specify it explicitly.
public fun map(transform: (Any) -> Unit): Flow = transform { value ->
^
(回傳的 Kotlin 版本kotlinc -version是“kotlinc-jvm 1.6.10 (JRE 17.0.1 1)”)
那么為什么 kotlinx.coroutines 中定義的代碼有效呢?如果我正確理解 Kotlin 的名稱陰影規則,它就不應該有。
uj5u.com熱心網友回復:
在 中kotlinx.couroutines,transform引數采用型別為 的引數T。因此,this.transform在使用transformlambda 引數呼叫時使用。
在您的示例中,transform引數采用型別為 的引數Any。一個 lambda 是 an Any,因此引數被使用而不是this.transform。Any用型別引數替換也會使您的代碼編譯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/395726.html
標籤:科特林
上一篇:Kotlin等價于java的Function<*,String>
下一篇:RecylerView資料未顯示
