Kotlin: Control Structures

If as an expression

fun bigger(a: Int, b: Int) = if (a > b) a else b

For loop

val list = listOf("A", "B", "C")
for (element in list) {
    println(element)
}

When expression

fun numberTypeName(x: Number) = when(x) {
0 -> "Zero" // Equality check
in 1..4 -> "Four or less" // Range check
5, 6, 7 -> "Five to seven" // Multiple values
is Byte -> "Byte" // Type check
else -> "Some number"
}

When expression with predicates

fun signAsString(x: Int)= when { 
    x < 0 -> "Negative" 
    x == 0 -> "Zero" 
    else -> "Positive" 
}

Leave a Reply

Your email address will not be published. Required fields are marked *