When Expression

Reading Time: 2 minutes

When Expression in kotlin contains different cases block. when the program is run, each case is tested one by one from top to bottom. If any matching case is found, the code inside that case block is executed. After that, the code next to when block is executed.

 

 
a is another number

When Expression as a Statement

When we use when expression in kotlin as a statement, you do  not necessarily have to use else block inside when block.

nothing printed out

a is 10. So, none of the case matches with a. Since there is no else statement, nothing will be printed on the console.

When Expression as an Expression

When we use when block in kotlin as an expression, you must use else block inside when block.


a is another number

When can also be used as a replacement for an ‘if-else if’ chain. If no argument is supplied , the branch conditions are simply boolean expressions.


Too young

Multiple conditions can be tested in one case as long as they are  all separated by commas.


Odd

You can use when expression as branch condition in when block. All the branch conditions must be unique for a given argument in when block.


a is less than b
multiple operation

Questions

I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂

 


 

Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a comment

stay informed!

Subscribe to receive exclusive content and notifications