Kotlin - Control flow as expressions

Introduction

An expression is a statement that evaluates to a value.

The following expression evaluates to true:

"hello".startsWith("h")

A statement has no resulting value returned.

The following is a statement, 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.

In Kotlin, the if...else and try...catch control flow blocks are expressions.

The result of if...else and try...catch can be assigned to a value, returned from a function, or passed as an argument to another function.

For example,

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 
} 

Here, 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.

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.