Learning Kotlin: return when

Submitted by Robert MacLean on Wed, 07/04/2018 - 09:00
**More Information** * This is the 13th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction) Continuing our break from the Koans today and going to look at another cool trick I learnt using Kotlin this week and focusing on the [when keyword we learnt about previously](/learning-kotlin-smart-casts); Let's start with a simple function to return the text for a value using when: fun step1(number: Int):String {     var result = "";     when (number) {         0 -> result = "Zero"         1 -> result = "One"         2 -> result = "Two"     }       return result; } The next evolution is we can avoid creating a variable and returning directly (this is something I would do often in .NET) fun step2(number: Int):String {     when (number) {         0 -> return "Zero"         1 -> return "One"         2 -> return "Two"     }       return "" } And now we get to the cool part, we can just return the when! fun step3(number: Int):String {     return when (number) {         0 -> "Zero"         1 -> "One"         2 -> "Two"         else -> ""     } } Yup, the when can return a value which means we can also do one final trick: fun step4(number: Int):String = when (number) {         0 -> "Zero"         1 -> "One"         2 -> "Two"         else -> ""     } It is so cool that your logic can just return from a condition, and it works with `if` statements too and even with the [Elvis operator](/learning-kotlin-kotlins-elvis-operator) we learnt yesterday: fun ifDemo3(name:String?) = name ?: "Mysterious Stranger"