Group Group Group Group Group Group Group Group Group

Returning values from when expressions

On page 105 we learn how we can return values from when expressions. These when expressions sort of makes me think of a switch statement in other languages, but I am trying to better understand what exactly gets returned.

The example provided is:

val numberName = when (number) {
  2 -> "two"
  4 -> "four"
  6 -> "six"
  8 -> "eight"
  10 -> "ten"
  else -> {
    println("Unknown number")
"Unknown"
 }
}
println(numberName) // > ten

When number for example is 11, the else block is executed, so we see Unknown number, followed by the last println statement which shows the returned value of Unknown.

While the first branches simply return a string, I’m curious how this else block works without a ‘return’ keyword or anything. When I try adding the return keyword before Unknown, I get an error that it was expecting a type of Unit and found a String. I guess I’m wondering how it knows to execute println() in the else block, but return Unknown

Hope that question makes sense. :slight_smile:

Thanks for the question @chuck_taylor! In Kotlin, the last expression in a block (denoted by the braces in the else case) is returned by the block, in this case the value of “Unknown”. The println call just executes normally before the value of “Unknown” is returned. The block itself is inferred to return a String, since the when expression cases besides the else all return strings.

The same would be true if you were assigning a value using an if-else expression. The if case could have a bunch of statements, and the last expression in the if case would be its return value, without the need for a return keyword. Same for the else case.

I hope that helps and thanks again!

That does help. Thank you for taking the time to read my question and reply. Just a bit of syntax to get used to I suppose. I am surprised though that using the return keyword throws an error - surprised I suppose that omitting ‘return’ is not optional.

However, thank you again for clarifying how it works!