English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to use if expressions in Kotlin with examples.
The syntax of if ... else is:
if (testExpression) {} //Run the code if testExpression is true } else { //Run the code if testExpression is false }
If the result of the testExpression is true, the specific part of the code within if is executed. It can have an optional else clause. If testExpression is false, the code in the else clause is executed.
fun main(args: Array<String>) { val number = -10 if (number > 0) { print("Positive") } else { print("Negative") } }
When running the program, the output is:
Negative
Unlike Java (and many other programming languages), if can be used as an expression in Kotlin; it returns a value.Recommended reading: Kotlin Expression
Here is an example:
fun main(args: Array<String>) { val number = -10 val result = if (number > 0) { "Positive" } else { "Negative" } println(result) }
When running the program, the output is:
Negative
When using if as an expression, the else clause is required.
If the body of the if only contains one statement, the braces are optional. For example,
fun main(args: Array<String>) { val number = -10 val result = if (number > 0) "Positive" else "Negative" println(result) }
This is similar toTernary operator in Java. Therefore, there is no ternary operator in Kotlin.
If the if branch block contains multiple expressions, the last expression is returned as the value of the block.
fun main(args: Array<String>) { val a = -9 val b = -11 val max = if (a > b) { println("$a is greater than $b.") println("The max variable saves the value of a.") a } else { println("$b is greater than $a.") println("The max variable saves the value of b.") b } println("max = $max") }
When running the program, the output is:
-9 Greater than -11. The max variable saves the value of a. max = -9
You can use if..else...if ladder to return a code block in many blocks of Kotlin.
fun main(args: Array<String>) { val number = 0 val result = if (number > 0) "Positive" else if (number < 0) "Negative" else "Zero" println("The number is $result") }
This program checks if the number is positive, negative, or zero.
An if expression can be nested within another if expression block, known as a nested if expression.
This program calculates the largest number among three numbers.
fun main(args: Array<String>) { val n1 = 3 val n2 = 5 val n3 = -2 val max = if (n1 > n2) { if (n1 > n3) n1 else n3 } else { if (n2 > n3) n2 else n3 } println("max = $max") }
When running the program, the output is:
max = 5