Kotlin – How to create an alias function of RxJava flatmap()?
我尝试为 Flowable.flatmap() 创建一个别名函数,如下所示,但编译错误。
|
1
2 3 |
fun <T, R> Flowable< T >.then(mapper: Function<T, Publisher<R>>): Flowable<R> {
return flatMap(mapper) } |
错误是:在 kotlin
中定义的接口 Function<out R> 需要一个类型参数
有什么想法吗?谢谢!
flatMap 需要一个 java.util.function.Function,实际上的错误是你没有在 Kotlin 文件中导入 java.util.function.Function,但我不建议你使用 java-8 函数,因为你可以\\不要利用 SAM 转换直接使用 Kotlin 代码中的 lambda,该代码使用 java-8 功能接口作为参数类型定义。
您应该将 Function 替换为 Function1,因为 Function 接口只是 Kotlin 标记接口。例如:
|
1
2 3 4 |
// v— use the `Function1<T,R>` here
fun <T, R> Flowable< T >.then(mapper: Function1<T, Publisher<R>>): Flowable<R> { return flatMap(mapper) } |
或者使用下面的 Kotlin 函数类型,例如:
|
1
2 3 4 |
// v— use the Kotlin function type here
fun <T, R> Flowable< T >.then(mapper: (T) -> Publisher<R>): Flowable<R> { return flatMap(mapper) } |
来源:https://www.codenong.com/45517872/
