If... (Conditionals)
Use if when you want to ask the computer a question. Kotlin’s style is similar to other languages, but it has a cool bonus.
Ask a question
val score = 85
if (score >= 80) {
println("You passed!")
}
Translation:
Remember score as 85 (it will not change)
If (score is greater than or equal to 80) {
print "You passed!"
}
No! (else)
if (score >= 80) {
println("Pass!")
} else {
println("Fail...")
}
Ask multiple times (else if)
When questions chain together, you can ask again.
if (score >= 90) {
println("Excellent")
} else if (score >= 80) {
println("Good")
} else {
println("Needs work")
}
Translation:
If (score is 90 or higher) { ... }
Otherwise, if (score is 80 or higher) { ... }
Otherwise { ... }
Kotlin’s secret move: the question box
In Kotlin, you can store the result of an if directly into a variable.
val result = if (score >= 80) "Pass" else "Fail"
println(result)
Translation:
If score is 80 or higher, put "Pass" into result; otherwise put "Fail"
Once you get used to it, your code becomes shorter and cleaner. And remember: the block ends where the braces close.