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. ![]()