Kotlin — Choosing a value with an if expression
Kotlin's if expression can initialize a value directly. Supply an else branch when using it in this way so both outcomes produce a result.
A simple example
Choose one value
- Start with n is 2
- Do this Choose by sign
- Result positive
fun main() {
val n = 2
println(if (n > 0) "positive" else "other")
}
positive
Choose a report value when a sample is missing
Report a whole-number average for a nonempty group and a text label for an empty group. Guard the division where the result is selected. Both branches in the example return a String. Only the chosen branch runs, which keeps the division away from a zero count.
A monitor displays the average of a sensor’s samples. If no sample arrived, show a message before attempting division. Three samples with a total of 18 give an average of 6.
Run the example
Use Kotlin 2.2 on the JVM. Run these commands from the directory containing the example.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
fun main() {
for (count in listOf(0, 3)) {
val label = if (count == 0) "no samples" else (18 / count).toString()
println(label)
}
}
no samples 6
The first group has zero samples and displays no samples. In the second group, 18 divided by 3 gives 6.
Try it yourself
What does an observed total of zero with three samples display?
Check your answer
It displays 0. This is a measured zero, whereas the empty group has no average.