Kotlin: using google-guava static methods as extensions

Can existing java static methods be used as extensions from a window?

Let's consider com.google.common.collect.Iterables.transform

. Now since I don't know how to deal with this, use the suggested method as an extension, I need 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 that, I could use it with iterators:

Iterable<A> input;
Function<A, B> function;
Iterable<B> output = input.transform(function);

      

But I think self-disclosure declaration is unnecessary. How to skip this declaration?


Update

There are two main subqueries in my question:

  • Can existing (static) methods be imported as extensions?

    No, this is not possible yet.

  • How to reuse existing guava Function

    s eg. to transform

    Iterable

    s?

    Instead, transform

    you should use an extension map

    as suggested in the answers. For reuse, Function

    you can use the extension like this:

public fun <T, R> Function<T, R>.asFun(): (T) -> R
    = { input -> apply(input) };

      

+3


source to share


1 answer


You shouldn't be putting Guava Java workarounds in Kotlin. Such an API is already part of the Kotlin runtime. Therefore, 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

Anything you can easily find in the IDE suggestions enter image description here

+4


source







All Articles