我尝试按照以下方法为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/

10-10 13:59
查看更多