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

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;

Let's start with a simple function to return the text for a value using when:

  1. fun step1(number: Int):String {
  2.     var result = "";
  3.     when (number) {
  4.         0 -> result = "Zero"
  5.         1 -> result = "One"
  6.         2 -> result = "Two"
  7.     }
  8.  
  9.     return result;
  10. }

The next evolution is we can avoid creating a variable and returning directly (this is something I would do often in .NET)

  1. fun step2(number: Int):String {
  2.     when (number) {
  3.         0 -> return "Zero"
  4.         1 -> return "One"
  5.         2 -> return "Two"
  6.     }
  7.  
  8.     return ""
  9. }

And now we get to the cool part, we can just return the when!

  1. fun step3(number: Int):String {
  2.     return when (number) {
  3.         0 -> "Zero"
  4.         1 -> "One"
  5.         2 -> "Two"
  6.         else -> ""
  7.     }
  8. }

Yup, the when can return a value which means we can also do one final trick:

  1. fun step4(number: Int):String = when (number) {
  2.         0 -> "Zero"
  3.         1 -> "One"
  4.         2 -> "Two"
  5.         else -> ""
  6.     }

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 we learnt yesterday:

  1. fun ifDemo3(name:String?) = name ?: "Mysterious Stranger"