Conditional Statement in Kotlin (if, when)

By | October 9, 2017

at first write a simple program then discuss

this program we read input from user in command line and convert it in Integer . In kotlin readLine() function is used to get input from command line .

If else condition in Kotlin is same in any other language . inside if block condition true then enter if block if not code enter else block .

this code also write in short form of if.. else cause inside of block has only one line bracket is not needed. But best practice is use bracket if block has one or multi line .

 

Nested If else example Grade Point :

here we write nested if else grade point program .

this program also we can write more easily using another system

this range is equivalent of (mark in 0..32) == (mark>=0 && mark<33)

Ranges:

Range expressions are formed with rangeTo functions that have the operator form .. which is complemented by in and !in. Range is defined for any comparable type, but for integral primitive types it has an optimized implementation. We learn ranges more details next part to tutorial series.

 

When Experssion

Another conditional statement using in every programming language that is SWITCH.  in kotlin switch is replace by when operator.

 when matches its argument against all branches sequentially until some branch condition is satisfied. whencan be used either as an expression or as a statement.

The else branch is evaluated if none of the other branch conditions are satisfied. If when is used as an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions.

 

Leave a Reply