Kotlin If Statement
Chapter:
Kotlin
Last Updated:
17-11-2017 08:02:46 UTC
Program:
/* ............... START ............... */
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")
}
/* ............... END ............... */
Output
Positive number
-8 is larger than -20.
Max Value : = -8
Notes:
-
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.
Tags
Kotlin , If Statement