我尝试创建 Flowable.flatmap()
的别名函数如下,但是编译错误。
fun <T, R> Flowable<T>.then(mapper: Function<T, Publisher<R>>): Flowable<R> {
return flatMap(mapper)
}
错误是:接口(interface)需要一个类型参数 Function<out R>
在 kotlin 中定义
有什么想法吗?谢谢!
最佳答案
flatMap
采用 java.util.function.Function
,实际错误是您没有导入 java.util.function.Function
在你的 Kotlin 文件中,但我不建议你使用 java-8函数,因为您无法利用 SAM Conversions直接使用 java-8 定义的 Kotlin 代码中的 lambda函数式接口(interface)作为参数类型。
您应该将 Function
替换为 Function1
,因为 Function
接口(interface)是 Kotlin marker interface仅有的。例如:
// v--- use the `Function1<T,R>` here
fun <T, R> Flowable<T>.then(mapper: Function1<T, Publisher<R>>): Flowable<R> {
return flatMap(mapper)
}
或使用 Kotlin function type例如如下:
// v--- use the Kotlin function type here
fun <T, R> Flowable<T>.then(mapper: (T) -> Publisher<R>): Flowable<R> {
return flatMap(mapper)
}
关于Kotlin - 如何创建 RxJava flatmap() 的别名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45517872/