Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bound Callable Reference Not Working With Reactor Subscribe

Tags:

kotlin

Since 1.1, Kotlin has had bound callable references. As I am on 1.1.3, I think I should be able to use the following to access the add method :

val elements = mutableListOf<Int>()

Flux.just(1, 2, 3, 4)
    .log()
    .subscribe(elements::add)

However, this throws an error:

elements::add error

I'm not sure what that error means in this specific instance. I can use .subscribe({ elements.add(it) }) with no issue, but shouldn't I be able to use the elements::add version?

like image 367
Mark Chandler Avatar asked Oct 24 '25 18:10

Mark Chandler


2 Answers

Kotlin Function Reference Expression is not like as java Method Reference Expression. the return type Any is not compatible with the return type Unit.

the error comes from the return type (Boolean) of the MutableList#add(Int) method is not compatible with the parameter parameter type (Int)->Unit of the subscribe method. so you can only using lambda expression this way.

you can using list::add in somewhere when both the parameter types and return type are compatible with the function. for example:

val add1:(Int) -> Boolean = list::add; // MutableList.add(Int);
val add2:(Int,Int) -> Unit = list::add; // MutableList.add(Int,Int);
like image 140
holi-java Avatar answered Oct 26 '25 13:10

holi-java


To rephrase and elaborate on the other answer: the problem is that a Consumer is expected, which takes an element and returns nothing in its single method. The corresponding function type for this in Kotlin would be (T) -> Unit.

The add method described in the MutableList interface however has the type (T) -> Boolean: it returns true if the element was successfully added (this is to support implementations of the interface that can't contain duplicates).

A possible solution to this is to add an extension method that adds an element to a MutableList without returning anything:

fun <T> MutableList<T>.addItem(element: T): Unit {
    this.add(element)
}

You can then use a bound callable reference to this extension, just like other MutableList methods:

Flux.just(1, 2, 3, 4)
        .log()
        .subscribe(elements::addItem)
like image 35
zsmb13 Avatar answered Oct 26 '25 14:10

zsmb13



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!