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:

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?
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With