1

I am trying to convert my Java class into Kotlin. This is the Java code:

Observable.just("Stacey")
    .zipWith(Observable.just(6),
    (name, age) -> {
        String text;
        if(age < 18){
            text = name + " is a child";
        }else{
            text = name + "is not a child";
        }
        return text;
    }
);

And this is what I converted it into:

Observable.just("Stacey")
.zipWith(Observable.just(6),
    BiFunction<String, Int, String> {name, age ->
        var text: String
        if(age < 18){
            text = "$name + is a child"
        }else{
            text = "$name + is not a child"
        }
        return text
    }
)

Lambda notation does not seem to work at all or I just cannot figure it out. All examples for BiFunctions in Kotlin that I found return a value directly like this

BiFunction {name, age -> name+age}

which is syntactically correct but I need some additional logic before I return something. Two error messages appear:

  • 'return' is not allowed here

  • Type mismatch. Required: Unit, Found: String

But I do want to return a string and I also explicitly declared it. But where else is there to put the return?

tir38
  • 9,810
  • 10
  • 64
  • 107
Yobuligo
  • 58
  • 1
  • 6

1 Answers1

1

I had this problem once too, all you have to do is to replace return text with return@BiFunction text

For explanations, you can have a look here:

Kotlin: Whats does "return@" mean?

https://tutorialwing.com/labeled-return-or-return-in-kotlin-with-example

acoria
  • 90
  • 1
  • 1
  • 8
  • 1
    @Yobuligo you can find more details in the [official documentation](https://kotlinlang.org/docs/reference/returns.html#return-at-labels) too – user2340612 Oct 08 '19 at 10:25