Kotlin Tutorial
Kotlin Classes
Conditional Statements (If..else)
So far, we learned Comparison Operators; Conditional Statements are all about them. They take decisions according to Boolean values; either true or false.
Note: Kotlin does not support ternary operators for conditions like ( condition ? then : else)
Kotlin got “if” as an expression which returns a value.
Syntax
if (condition) {
// code which executes if the condition is true
}
Note: “If” expression is in lowercase; uppercase “IF” will throw a compile time error
Normal usage of if..else:
Example:
var a = 20
if (a > 30) {
println("a is greater than 30")
} else {
println("a is less than 30")
}
The code above outputs:
a is less than 30
Kotlin If as expression
var a = 20
result = if (a > 30) {
"a is greater than 30"
} else {
"a is less than 30"
}
println(result)
The code above outputs:
a is less than 30
“else” is mandatory if you are using if as an expression.
Let’s see another example:
Change the value of variable bulb to false and RUN the code again you will see the different output.
var bulb : Boolean = true
var result = if (bulb == true) {
"Bulb is on"
} else {
"Bulb is off"
}
println(result)
The following code outputs:
Bulb is on
Note: You can omit the curly braces {} when “if” has only one statement. .
if (bulb == true) "bulb is on" else "bulb is off"
This is quite similar to the ternary operator in Java; but Kotin does not support it.
If..else Ladder
You can take multiple decisions using if..else Or we can say (ladder if..else..if..else), for example
var number = 20
if (number < 0) {
println("$number is negative")
} else if (number > 0) {
println("$number is positive")
} else {
println("$number is Zero")
}
The code above outputs:
20 is positive
Or you also can do
var number = 20
var result = if (number < 0) {
"$number is negative"
} else if (number > 0) {
"$number is positive"
} else {
"$number is Zero"
}
print(result)
Output will be the same.
In the above example the 2nd condition is true: change the number value to 0 and RUN it