when expression

Unlike other C-style languages, Kotlin doesn't have a switch statement, but a when expression that is a lot more flexible:

val x: Int = /*Some unknown value here*/

when (x) {
0 -> println("x is zero")
1, 2 -> println("x is 1 or 2")
in 3..5 -> println("x is between 3 and 5")
else -> println("x is bigger than 5... or maybe is negative...")
}

when are expressions:

val message = when {
2 > 1 -> "2 is greater than 1"
else -> "This never gonna happen"
}

println(message)

And they also can be used to replace if expression:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.118.229