在 Kotlin 函数类型中表达 "super" 泛型?
Expressing "super" generics in Kotlin functional types?
我正在尝试移植 RxJava 库并利用 Kotlin 中的扩展函数。
fun <T,R: MutableCollection<T>> Observable<T>.collectWhile(factory: (() -> R), condition: (R,T) -> Boolean) =
compose(Transformers.collectWhile(factory,condition))
Transformers.collectWhile()
写在 Java 中并具有此签名:
public static <T, R extends Collection<T>> Transformer<T, R> collectWhile(final Func0<R> factory,
final Action2<? super R, ? super T> collect)
但是,我在映射 collect
参数时遇到问题,而且我不擅长泛型。如何用函数类型表达 super
?
更新
我犯了一个愚蠢的错误。我不应该在深夜发帖。
我实际上是针对这个
public static <T, R extends Iterable<?>> Transformer<T, R> collectWhile(final Func0<R> factory,
final Action2<? super R, ? super T> collect, final Func2<? super R, ? super T, Boolean> condition)
这是我应该做的。
fun <T,R: MutableCollection<T>> Observable<T>.collectWhile(factory: (() -> R), action: (R,T) -> Unit, condition: (R,T) -> Boolean) =
compose(Transformers.collectWhile(factory,action,condition))
Java通配符类型? super T
对应Kotlin中的in T
use-site type projection,所以collect
参数对应的类型为Action2<in R, in T>
.
该类型大致等效(或更具体地说,符合 Function2 类型参数的 SAM-conversion) to (R, T) -> Unit
functional type in Kotlin, because (R, T) -> Unit
is a synonym for type Function2<R, T, Unit>
and the latter is equivalent to Function2<in R, in T, out Unit>
due to the declaration-site variance。
您不能将类型为 (R, T) -> Boolean
的函数作为参数传递给 collect
,其中应为 (R, T) -> Unit
。
要么更改 collect
参数的类型,要么更改 condition
参数的类型。
我正在尝试移植 RxJava 库并利用 Kotlin 中的扩展函数。
fun <T,R: MutableCollection<T>> Observable<T>.collectWhile(factory: (() -> R), condition: (R,T) -> Boolean) =
compose(Transformers.collectWhile(factory,condition))
Transformers.collectWhile()
写在 Java 中并具有此签名:
public static <T, R extends Collection<T>> Transformer<T, R> collectWhile(final Func0<R> factory,
final Action2<? super R, ? super T> collect)
但是,我在映射 collect
参数时遇到问题,而且我不擅长泛型。如何用函数类型表达 super
?
更新
我犯了一个愚蠢的错误。我不应该在深夜发帖。
我实际上是针对这个
public static <T, R extends Iterable<?>> Transformer<T, R> collectWhile(final Func0<R> factory,
final Action2<? super R, ? super T> collect, final Func2<? super R, ? super T, Boolean> condition)
这是我应该做的。
fun <T,R: MutableCollection<T>> Observable<T>.collectWhile(factory: (() -> R), action: (R,T) -> Unit, condition: (R,T) -> Boolean) =
compose(Transformers.collectWhile(factory,action,condition))
Java通配符类型? super T
对应Kotlin中的in T
use-site type projection,所以collect
参数对应的类型为Action2<in R, in T>
.
该类型大致等效(或更具体地说,符合 Function2 类型参数的 SAM-conversion) to (R, T) -> Unit
functional type in Kotlin, because (R, T) -> Unit
is a synonym for type Function2<R, T, Unit>
and the latter is equivalent to Function2<in R, in T, out Unit>
due to the declaration-site variance。
您不能将类型为 (R, T) -> Boolean
的函数作为参数传递给 collect
,其中应为 (R, T) -> Unit
。
要么更改 collect
参数的类型,要么更改 condition
参数的类型。