3

I have this code in Java:

Flowable.just(1,2,3)
        .flatMap(Flowable::just);

and this code in Kotlin:

Flowable.just(1,2,3)
        .flatMap(Flowable::just)

While Java code compiles fine, Kotlin compiler says: "Error:(47, 30) Kotlin: One type argument expected for class Flowable : Publisher defined in io.reactivex"

However this compiles fine:

Flowable.just(1,2,3)
        .flatMap { Flowable.just(it) }

What am I doing wrong or how come Kotlin can't infer the type of Flowable automatically?

  • From [Kotlin docs](https://kotlinlang.org/docs/reference/lambdas.html): "A lambda expression is always surrounded by curly braces." – Abhijit Sarkar Aug 13 '17 at 08:44

1 Answers1

3

This is not quite an answer, but it's too long for a comment.

In the first case that does not compile, the error has to do with Kotlin not selecting the correct Flowable::just method to pass to Flowable.flatMap(...). There are 10 different Flowable.just(...) methods defined where the difference is the number of arguments.

In the second case, you are passing Flowable.flatMap() a lambda that explicitly calls the single parameter version of Flowable.just() (i.e., the one parameter version).

In the first case, Kotlin is apparently choosing one of the other ten Flowable::just methods instead of looking for one that matches the signature expected by Flowable.flatMap() (of which there are 12 defined). In contrast, Java is able to deduce (from the signature of the parameter) which of the many overloads of .just() to pass.

This may be a Kotlin shortcoming, but I would like to hear what one of the Kotlin compiler experts have to say.

Les
  • 10,335
  • 4
  • 40
  • 60