Home > Mobile >  Why is Result.map in Kotlin behaving diferently for Unit types?
Why is Result.map in Kotlin behaving diferently for Unit types?

Time:10-21

I am confused about the following two Kotlin code snippets:

A:

val r: Result<Unit> = Result.success(Unit).map { Result.success(Unit) }

B:

val r: Result<Int> = Result.success(Unit).map { Result.success(1) }

Snippet A compiles while snippet B does not compile.

Can someone explain why snippet A works with the Kotlin type system.

CodePudding user response:

You're not supposed to return a Result from the map lambda. You're supposed to return a value that will be wrapped in a Result. That's why your code B fails. It would succeed with just map { 1 }.

Code A succeeds because when Kotlin expects a lambda to return Unit, it implicitly returns Unit regardless of what the last line of code in the lambda is. If it didn't do this, any lambda that has no return value would have to end with a line that says Unit. In the same way, any function with no explicit return value has an implicit return type of Unit, but the compiler does not require you to explicitly write return Unit at the end of your functions.

  • Related