Kotlin for Enterprise Applications using Java EE
上QQ阅读APP看书,第一时间看更新

Expressions over statements

A statement is an element of a program that represents an action. An expression is a part of the statement that gets evaluated to a value. Statements introduce mutability. The more statements a program contains, the more mutability it will have. Mutability in code increases the chance that it is erroneous. Expressions, on the other hand, do not produce mutability. In purely functional constructs, there are no statements, there are only expressions. More expressions in a program mean less mutability and code that is more concise.

Consider the code for 5_Expressions.kts:

val number = 5
val evenOrOdd = if(number % 2 == 0) "is even number" else "is odd number"
println("$number $evenOrOdd")

The output is as follows:

In this case, the code has expressions and we are not mutating any state. We are simply assigning the result of an expression to a variable and printing it.

Similarly, try...catch is also an expression. try...catch is used for handling the exceptions. The last statement in the try block becomes the expression for the try block.