Kotlin Control flow as expressions tutorial

An expression is a statement that evaluates to a value. The following expression evaluates to true:
“hello”.startsWith(“h”)
A statement, on the other hand, has no resulting value returned. The following is a statement because it assigns a value to a variable, but does not evaluate to anything itself:
val a = 1
In Java, the common control flow blocks, such as
if…else
and
try..catch
, are statements. They do not evaluate to a value, so it is common in Java, when using these, to assign the results to a variable initialized outside the block:

public boolean isZero(int x) {
      boolean isZero;
      if (x == 0)
        isZero = true;
      else
        isZero = false;
      return isZero;
    }

In Kotlin, the
if…else
and
try..catch
control flow blocks are expressions. This means the result can be directly assigned to a value, returned from a function, or passed as an argument to another function.

This small, yet powerful, feature allows boilerplate to be reduced, code made more readable, and the use of mutable variables avoided. The typical use case of declaring a variable outside of an if statement to then initialize it inside either branch can be avoided completely:

val date = Date()
    val today = if (date.year == 2016) true else false
    fun isZero(x: Int): Boolean {
      return if (x == 0) true else false
    }

A similar technique can be used for try..catch blocks, which is as follows:

val success = try {
      readFile()
      true
    } catch (e: IOException) {
      false
    }

In that example, the success variable will contain the result of the try block only if it completes successfully; otherwise the catch clause return value will be used, in this case false.
Expressions need not be single lines. They can be blocks, of course, and in those cases the last line must be an expression, and that expression is the value that the block evaluates to. When using if as an expression, you must include the else clause. Otherwise the compiler will not know what to do if the if did not evaluate to true. If you do not include the else clause, the compiler will display a compile time error.

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn