Kotlin Fundamental

When expression in Kotlin

Pinterest LinkedIn Tumblr

in this post, we’ll learn when as expression, Now this when is actually the replacement of switch case statement similar to java, So let us explore when expression in Kotlin

fun main(args: Array<String>) {
    val x = 2
}

Let the above code block, here we simply define one variable is x and it is final.

WHEN statement

Now instated of writing switch case statement that we used to in case of java, Here we have the when expression. Let us write code 

Let say the value of x is equal to 1, then simply put dash followed by arrow than simply write the code.  Similarly the value of x is equal to 2 then execute line of code. 

fun main(args: Array<String>) {
    val x = 2
    when (x) {
        1 -> print("x is 1")
        2 -> print("x is 2")
    }
}

Now let us run the code, so we get the output as “x is 2”. Now here notice we don’t have to write any break statement or the continue statement.

Default Statement

Now similar to java we also have a default statement in case of when clause. The default statement in the case of when actually represented with help of else. So we need to write else part here. Now again syntax is a dash followed by an arrow (->).

fun main(args: Array<String>) {
    val x = 7
    when (x) {
        1 -> print("x is 1")
        2 -> print("x is 2")
        else -> {
            print("x value is unknown")
        }
    }
}

Now let us change the x value is 7 and run the code then we get 

x value is unknown
Process finished with exit code 0

Just because value is 7 and we have written code just for 1 & 2, not for 7 that is why the else part is executed.

Multiple conditions in one statement

Now we can have also multiple conditions inside the statement. Means, In this block we can write multiple conditions Like below. 

Now suppose x value is 0, and you want to execute multiple condition in just one statement, what you can do is, you can do  simply use 0,5 ->

fun main(args: Array<String>) {
    val x = 5
    when (x) {
        1, 5 -> print("x is 1 or 5")
        2 -> print("x is 2")
        else -> {
            print("x value is unknown")
        }
    }
}

In this example you define like 1,2,4, in is single line statement. Now lets run the code in output console you have like below

x is 1 or 5
Process finished with exit code 0

Range uses when expression

Apart from this, we can also use range in case of value here. Let’s say x is equal to 12 right. Now suppose here I’m used range 1..15. How we do that

 fun main(args: Array<String>) {
    val x = 12
    when (x) {
        in 1..15 -> print("x is 1 or 5")
        2 -> print("x is 2")
        else -> {
            print("x value is unknown")
        }
    }
}

So this 1..15 is contains value 1 to 15, which also include value 12 as well , So this condition simply return true

Operator with Range

In the same way we can also use not(!) operator here, Just put this operator like below

fun main(args: Array<String>) {
    val x = 13
    when (x) {
        !in 1..15 -> print("x is 1 or 5")
        2 -> print("x is 2")
        else -> {
            print("x value is unknown")
        }
    }
}

In this block, when conditions become false here then compilers look for simple matches here. And again it won’t find the match then by default it will execute the else part here

Now let us run the code and see on console, Output will be like below . 

x value is unknown
Process finished with exit code 0
 

WHEN as Expression

Suppose if I define a variable, let say var result:String, Now let us change this when statement as expression, In this case simply we assign result wich when statement using the equal sign. 

fun main(args: Array<String>) {
    val x = 1
    val result = when (x) {
        1 -> "x is 1"
        2 -> "x is 2"
        else -> {
            "x value is unknown"
        }
    }
    print(result)
}

Now here, what is happening here when the condition is actually matched then it will simply return the match value. And this value will assign to result variable.

Multiple statement in a block

Now suppose If I will write two statements inside one block. In this situation what will happen because we have two string expressions inside the else block. Lets us run the code and see

fun main(args: Array<String>) {
    val x = 5
    val result = when (x) {
        1 -> "x is 1"
        2 -> "x is 2"
        else -> {
            "x value is unknown"
            "x is a magic number"
        }
    }
    print(result)
}

The output is

x is a magic number
Process finished with exit code 0

As you see we are getting a second expression. What happened is that whatever statement we have inside the code at the end, that actually returns. We saw the last expression is actually executed.

So always remember this, whatever you write the end of the code block it actually return.

Conclusion

This is all about when expression, here the when statement actually acting expression and returning some value, In Kotlin, forgot about switch statement and simply adapt to when expression. Thank for reading, Have a Good Day.

Write A Comment