首页 文章

Kotlin - 如何创建RxJava flatmap()的别名函数?

提问于
浏览
3

我尝试为 Flowable.flatmap() 创建一个别名函数,如下所示,但编译错误 .

fun <T, R> Flowable<T>.then(mapper: Function<T, Publisher<R>>): Flowable<R> {
  return flatMap(mapper)
}

错误是: One type argument expected for interface Function<out R> defined in kotlin

有什么想法吗?谢谢!

1 回答

  • 1

    flatMap 需要一个 java.util.function.Function ,实际错误是你没有在你的Kotlin文件中导入 java.util.function.Function ,但是我不建议你使用java-8函数,因为你不能利用SAM Conversions来直接使用lambda来自Kotlin代码,用java-8功能接口定义为参数类型 .

    您应该将 Function 替换为 Function1 ,因为 Function 接口仅为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)
    }
    

    OR 使用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)
    }
    

相关问题