是否可以使用现有的 java 静态方法作为开箱即用的扩展?
让我们考虑 com.google.common.collect.Iterables.transform
。现在,因为我不知道如何处理这个问题,所以要使用建议的方法作为扩展,我必须这样写:
import com.google.common.collect.Iterables.transform
public fun <F, T> Iterable<F>.transform(function: Function<in F, out T>) : Iterable<T> {
return transform(this, function);
}
因此,在此之后我可以将它与可迭代对象一起使用:
Iterable<A> input;
Function<A, B> function;
Iterable<B> output = input.transform(function);
但我认为自己声明扩展是不必要的。如何省略这个声明?
更新
我的问题有两个主要子问题:
是否可以将现有(静态)方法作为扩展导入?
不,目前还不可能。
如何重用现有的 guava 的
Function
,例如到transform
Iterable
s?而不是
transform
您应该使用map
扩展,如答案中所建议的。要重用Function
,可以像这样使用扩展:
public fun <T, R> Function<T, R>.asFun(): (T) -> R
= { input -> apply(input) };
最佳答案
您不应该将 Guava 的 Java 变通方法带入 Kotlin。这样的 API 已经是 Kotlin 运行时的一部分。所以你可以这样写:
val input = listOf(1,2,4,8)
val output = input.map { /*transform function*/ it + 1 }
http://kotlinlang.org/api/latest/jvm/stdlib/kotlin/map.html
您可以在 IDE 的建议中轻松发现的所有其他内容
关于guava - Kotlin:使用 google-guava 静态方法作为扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27410629/