Is it possible to use existing java static methods as extensions from the box?
Lets consider com.google.common.collect.Iterables.transform. Now, because I don't know how to deal with this, to use proposed method as the extension, I have to write something like:
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);
}
So, after this I could use it with iterables:
Iterable<A> input;
Function<A, B> function;
Iterable<B> output = input.transform(function);
But I think that declaring extension myself is unnecessary. How to omit this declaration?
Update
My question has two main subquestions:
Is it possible to import existing (static) methods as extensions?
No, for now it isn't possible.
How to reuse existing guava's Functions, e.g. to transform Iterables?
Instead of transform you should use map extension, as proposed in answers. To reuse Functions it is possible to use extension like this:
public fun <T, R> Function<T, R>.asFun(): (T) -> R
= { input -> apply(input) };
You shouldn't bring Guava's workarounds for Java into Kotlin. Such API is already a part of Kotlin runtime. So you can write:
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
All others you can easily discover in IDE's suggestions

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With