Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | fun main(args: Array<String>) { /*Traditional if else statement in Programming. if (testExpression) { Run if testExpression is true } else { Run if testExpression is false } */ val number = 100 val result = if (number > 0) { "Positive number" } else { "Negative number" } println(result) val val1 = -8 val val2 = -20 val max = if (val1 > val2) { println("$val1 is larger than $val2.") val1 // Returning value } else { println("$val1 is larger than $val2.") val2 } println("Max Value : = $max") } |
Output:
1 2 3 4 5 | Positive number -8 is larger than -20. Max Value : = -8 |
If statement in Kotlin is different from traditional if statment in programming.
In Kotlin if expression returns a value and store into a variable.
In Kotlin else branch is mandatory when we use if expression. But in java it will allow with only if statment.
Please refer to the above program to get more understanding about if statement in Kotlin.