Certainly! The if-else
statement in Kotlin is used for conditional execution of code blocks. It allows you to execute different blocks of code based on whether a condition is true or false. Here's a simple explanation with an example:
Example
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Let's say we want to check if a person is eligible to vote based on their age:
fun main() {
val age = 18
if (age >= 18) {
println("You are eligible to vote")
} else {
println("You are not eligible to vote")
}
}
You are eligible to vote
age
representing the person's age.if
statement checks if the age
is greater than or equal to 18
.true
, the message "You are eligible to vote" is printed.false
, the message "You are not eligible to vote" is printed.if-else
StatementsYou can also nest if-else
statements within each other for more complex conditions.
Example
fun main() {
val score = 75
if (score >= 90) {
println("You got an A")
} else if (score >= 80) {
println("You got a B")
} else if (score >= 70) {
println("You got a C")
} else {
println("You need to improve")
}
}
You got a C
The if-else
statement is a fundamental control flow construct in Kotlin that allows you to execute different blocks of code based on conditions. It's commonly used for decision-making in programs, enabling you to create more dynamic and flexible code.