×

Search anything:

When in Kotlin

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 20 minutes

When is one of the control flow of Kotlin. If you are coming from java, When is a bit similar to Switch. Even if you don't know java, think When as powerful nested if else. If you don't know any programming language, then think When as a plain enlglish term WHEN.

It's pretty self-explanatory, Right?

Syntax

Here is syntax

    var x = 0
    when(x){
        0 -> print("I'm Zero")
        1 -> print("I'm One")
        2, 3 -> println("I might be Two to There")
        else -> println("I don't know who I am")
    }

Explanation

Here is explanation.

  1. take a name x and assign an Int value of 0
  2. when x is
  3. 0 then show I'm Zero ( or we might said print out I'm Zero )
  4. when x is 1 then I'm One
  5. when x is 2 or 3 then I might be Two or Three
  6. here println is not the same as print
  7. println means print out as a line then wait at the next line
  8. print means print out but don't move to next line
  9. now the last one else, that means none of the above
  10. In our case when x is not 1, 2 or 3 than else will do his job. Here is just print out I don't know who I am

Round Two

    val me = "Whale"
    when(me){
        "Human" -> println("I'm human, Yayyy!")
        "Fox" -> println("I'm Fox, but not Megan Fox")
    }
  1. Above code will not print Anything
  2. Why ?
  3. Coz when above code execute nothing matched with the given variable (or immutalbe variable) me.

Let's fix it

    val me = "Whale"
    when(me){
        "Human" -> println("I'm human, Yayyy!")
        "Fox" -> println("I'm Fox, but not Megan Fox")
        "whale" -> println("I'm whale, but small one")
        "Whale" -> println("I'm Whale, but not so small")
    }

So what is your guess ?

if you said I'm whale, but small one you are WRONG
you know computer are dumb, so they only know what you teached them to know. Case Sentitive Right?
The answer is I'm Whale, but not so small
but above code have some problem !
change the assign value of me to "Jedi"
here is code

    val me = "Jedi"
    when(me){
        "Human" -> println("I'm human, Yayyy!")
        "Fox" -> println("I'm Fox, but not Megan Fox")
        "whale" -> println("I'm whale, but small one")
        "Whale" -> println("I'm Whale, but not so small")
    }

you gonna see nothing, coz we missed none of the above part
(or else).

so when can used not just for Int, String but also for whole other types. boolean, range, char, double, etc etc

Round Three

    var howMuchIHave = 0.0
    when(howMuchIHave){
        0 -> { // Incompatible types: Int and Double at here
            print("I have zero")
            print("ohh poor me!")
        }
        0.0 -> {
            println("I still don't have money")
            println("I have to rob the bank, just kidding")
        }
        else -> println("How much I have is $howMuchIHave")
    }

Above code will print
Incompatible types: Int and Double
you know // means comment right?
the problem here is we are performing different type all together.

here is the fix

    var howMuchIHave = 0.0
    when(howMuchIHave){
        0.0 -> { // Incompatible types: Int and Double at here
            print("I have zero")
            print("ohh poor me!")
        }
        0.0 -> {
            println("I still don't have money")
            println("I have to rob the bank, just kidding")
        }
        else -> println("How much I have is $howMuchIHave")
    }

print out I have zeroohh poor me!
Hummm why? we have two 0.0 but only one print out.
coz we have duplicate label in when
but did you noticed about the difference between print and println
that is progress.

    var howMuchIHave = 0.1
    when(howMuchIHave){
        0.0 -> { // Incompatible types: Int and Double at here
            print("I have zero")
            print("ohh poor me!")
        }
        0.1 -> {
            println("Something is better than nothing")
            println("One small penny for man, one giant leap for me")
        }
        else -> println("How much I have is $howMuchIHave")
    }

now the output is
Something is better than nothing
One small penny for man, one giant leap for me

so here is your task change the var howMuchIHave = 0.1 to
var howMuchIHave = 'a'
comment the output

press me to the kotlin online ide

Round Four

    var something = "something"
    when(something){
        is String -> println("I'm a String")
        "something" -> println("My value is something")
        else -> println("I'm nothing")
    }

here will print out I'm a String
so change the order to above code to

    when(something){
       "something" -> println("My value is something")
       is String -> println("I'm a String")
       else -> println("I'm nothing")
   }

this time will be My value is something print out

  1. is keyword check the type of the instance
  2. code order is important

Round Five

    val x = 1101
    when(x){
        in 0..1 -> println("between 0 and 1")
        !in 1100..1101 -> println("not between 1000 and 1111")
        in 1100..1101 -> println("between 1100 and 1101")
        else -> println("I have no idea at all")
    }

above code will print out between 1100 and 1101

  1. .. is called Range operator in kotlin
  2. in 0..1 means between 0 and 1
  3. !in means not in
  4. so !in 1100..1101 means not between 1100 and 1101

Round Six

    val number = 2
    when{
        number.isEven() -> prinltn("Even number")
        number.isOdd() -> println("Odd number")
        else -> println("error")
    }

here, we used when liked if else

Round Seven

      var responseCode = 400
      val errorMessage = when(responseCode){
      200 -> "Ok"
      201 -> "Created"
      203 -> "Non-Authoritative Information"
      400 -> "Bad Request"
      403 -> "Forbidden"
      500 -> "Internal Server Error"
      else -> "Unknown Error"
   }
   println("HTTP Status Code is $responseCode and result is $errorMessage")

The output is HTTP Status Code is 400 and result is Bad Request

When responseCode is something that match within my code I'll take that value and passed to variable named errorMessage.

What important is when you used when liked that, don't forget the else part. change the responseCode to 501 and
remove or comment else -> "Unknown Error sentence.
Run it.
Comment your output

When in Kotlin
Share this