2
votes

I am trying to call the following Java method from Kotlin:

KStream<K, V>[] branch(final Predicate<? super K, ? super V>... predicates);

This method is part of the Kafka Streams API.

The way I tried to call it, following the Kotlin docs, was by defining an extension method:

fun <K, V> KStream<K, V>.kbranch(vararg predicates: (K, V) -> Boolean):
    Array<KStream<K, V>> = this.branch(*predicates)

The problem is that it doesn't compile. I get the following error:

Type mismatch: inferred type is Array<out (K, V) -> Boolean> 
but Array<(out) Predicate<in K!, in V!>!>! was expected

The similar KStream#filter method, which accepts a single Predicate as an argument, can be called without any issue when passing a Kotlin lambda with the same signature of (K, V) -> Boolean.

Any ideas? I have seen this similar question, but something here seems subtly different and I can't pinpoint it.

2

2 Answers

3
votes

Unfortunately SAM conversion is not supported for variable length arguments. You can work around it though by converting the (K, V) -> Boolean to Predicate<K,V> yourself like so:

fun <K, V> KStream<K, V>.kbranch(vararg predicates: (K, V) -> Boolean): Array<KStream<K, V>> {
    val arguments = predicates.map { Predicate { key: K, value: V -> it(key, value) } }
    return this.branch(*arguments.toTypedArray())
}
0
votes

Actually you can define like this.

fun <in K, in V> KStream<K, V>.kbranch(vararg predicates: out Predicate<K, V>):
    Array<KStream<K, V>> = this.branch(*predicates)