Aleph Publications

Learn. Grow. Lead.

Kotlin and Expressions

2 min readJun 11, 2020

--

In most programming languages and are known as control flow statements, but in Kotlin and (the equivalent of ) can be used as expressions as well. Let’s explore what this means.

What is a Statement?

A statement is a syntactic unit of instructions to the computer. This is a prime characteristic of imperative programming languages. The unit of instructions let the computer know-how to achieve something step by step. Programs written in imperative programming languages are a sequence of one or more statements, i.e. multiple instruction sets to be executed one after the other.

What is an Expression?

An expression is a synthetic unit that returns a value. Unlike languages like Java, and in Kotlin can return a value and therefore can be used both as traditional control flow statements or as expressions. Let’s look at some examples.

Used as an expression, the control flow returns a value.

If as an expression

The code snippet above shows how the expression produces a value and returns it. The expression compares the values and and assigns the produced value to the variable .

When using as an expression, there must always be an branch. If not, the compiler throws an error — ‘if’ must have both main and ‘else’ branches if used as an expression.

‘if’ must have both main and ‘else’ branches

Similarly, should also always have an branch when used as an expression. See the example below.

‘when’ expression must be exhaustive

To summarise, in Kotlin and can be used as either statements or expressions. A statement is a set of instructions given to the computer to get something done whereas expression is a synthetic unit that produces a value.

--

--

Panduka Wedisinghe
Panduka Wedisinghe

Written by Panduka Wedisinghe

Android Developer/Flutter Developer/iOS Developer/Machine Learning Enthusiast

No responses yet