How to resolve conflict of default extension with 3rd-party library?


#1

Hello. I’m trying to rewrite one of the existing modules in Kotlin to test it out. But I have a problem with default function resolution.

So I’m using aol/cyclops-react library. There is a class LazyFutureStream, that has it’s own method forEach. This method doesn’t just goes over iterator, it does something more complicated. So I need to use it. But kotlin.collections.forEach is imported by default and hides this overriden method. How can I NOT use this extension??

I have this code on Java:

    LazyReact.parallelBuilder()
            .from(IntStream.of(1, 2, 3, 4))
            .forEach((it) -> {
                System.out.println(it);
            });

And this is Kotlin:

        LazyReact.parallelBuilder()
                .from(IntStream.of(1,2,3,4))
                .forEach {
                    println(it)
                }

Any help appritiated.


#2

Hello!

Hiding member for Iterable<T>.forEach is necessary to avoid implicit semantic change after code used with JDK 6 gets compiled with JDK 8.

But you still can call the member if you’d like with help of SAM constructor:

        LazyReact.parallelBuilder()
                .from(IntStream.of(1,2,3,4))
                .forEach(Consumer {
                    println(it)
                })

Unfortunately, it’s not that shiny as a plain lambda, but you can add an extension with a different name that does exactly the thing:

fun <T> Iterable<T>.myForEach(x: (T) -> Unit) = this.forEach(java.util.function.Consumer(x))

#3

Thanks a lot, both solutions worked perfectly!