The if { ... } else { ... } expression

In Kotlin, the if control flow element can be used in the same way as it is used in Java. The following example demonstrates the use of if as a usual statement:

fun ifStatement() {
val a = 4
if (a < 5) {
println(a)
}
}

If you are using the if { ... } else { ... } control flow element as an expression, you have to declare the else block, as follows:

fun ifExpression() {
val a = 5
val b = 4
val max = if (a > b) a else b
}

The preceding example shows that if { ... } else { ... } returns a value.

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

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