Kotlin if Expression
The if
expression is used to make decisions based on a condition. In Kotlin, if
is an expression, which means that it returns a value.
Syntax
if (condition) {
// Code to be executed if condition is true
} else {
// Code to be executed if condition is false
}
Example
fun main() {
val number = 10
val result = if (number % 2 == 0) {
"Even"
} else {
"Odd"
}
println(result)
}
Output
Even
Explanation
In the example, the if
expression checks whether the number
variable is even or odd. If the condition number % 2 == 0
is true, the expression returns the string "Even"
. Otherwise, it returns the string "Odd"
. The resulting value is assigned to the result
variable, which is then printed to the console.
Use
The if
expression is commonly used for making decisions in code. It's often used in combination with other expressions, such as when expressions and try-catch blocks.
Important Points
- The
if
expression is used to make decisions based on a condition. - In Kotlin,
if
is an expression that returns a value. - The
if
expression can be used with or without theelse
keyword. - The
if
expression can be used in combination with other expressions, such as when expressions and try-catch blocks.
Summary
The if
expression is a powerful tool in Kotlin for making decisions based on conditions. It's an expression that returns a value, which makes it more flexible than a if
statement. The if
expression can be used in a variety of situations, and it's an essential tool for any Kotlin developer's toolbelt.