我尝试按照以下方法为Flowable.flatmap()
创建一个别名函数,但编译错误。
fun <T, R> Flowable<T>.then(mapper: Function<T, Publisher<R>>): Flowable<R> {
return flatMap(mapper)
}
错误是:在kotlin 中定义的接口(interface)
Function<out R>
期望的一种类型参数有什么想法吗谢谢!
最佳答案
flatMap
接受java.util.function.Function
,实际的错误是您没有将Kotlin文件中的java.util.function.Function
导入,但是我不建议您使用java-8函数,因为您无法利用SAM Conversions直接从用java-8功能接口(interface)定义为参数类型的Kotlin代码。
您应该将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 - Kotlin-如何创建RxJava flatmap()的别名函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45517872/