Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: using google-guava static methods as extensions

Tags:

kotlin

guava

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:

  1. Is it possible to import existing (static) methods as extensions?

    No, for now it isn't possible.

  2. 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) };
like image 337
Timofey Gorshkov Avatar asked Mar 22 '26 15:03

Timofey Gorshkov


1 Answers

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 enter image description here

like image 67
Oleksii Masnyi Avatar answered Mar 25 '26 00:03

Oleksii Masnyi



Donate For Us

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