The linked challenge link does not work with reactor Subscribe

Since 1.1, Kotlin has had linked referencing. Since I am on 1.1.3 I think I should use the following to access the method add

:

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 this error means in this particular instance. I can use .subscribe({ elements.add(it) })

without problem, but shouldn't I be using the version elements::add

?

+3


source to share


2 answers


Kotlin Function Reference The Expression is not like the java Method Reference Expression. the return type is Any

incompatible with the return type Unit

.

the error arises from the return type (Boolean) of the method is MutableList#add(Int)

incompatible with the parameter type of the (Int)->Unit

method parameter subscribe

. so you can only use lambda expression this way.



you can use list::add

anywhere when both parameter types and return type are compatible with the function. eg:

val add1:(Int) -> Boolean = list::add; // MutableList.add(Int);
val add2:(Int,Int) -> Unit = list::add; // MutableList.add(Int,Int);

      

+2


source


To rephrase and clarify another answer: the problem is what is expected Consumer

, which takes an element and returns nothing in its single method. The appropriate function type for this in Kotlin would be (T) -> Unit

.

The method add

described in the interface MutableList

, however, has a type (T) -> Boolean

: it returns true if the element was (this is support for interface implementations that cannot contain duplicates).

A possible solution to this is to add an extension method that adds the item to MutableList

without returning anything:



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

      

Then you can use a bindable reference to this extension like other methods MutableList

:

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

      

+2


source







All Articles