Archive for June 16, 2019

Control Expressions in Kotlin

Posted: June 16, 2019 in Kotlin
Tags: ,

In any imperative programming language, an expression is a line or fragment of code that is computed to produce a value whereas statement is a standalone unit of the program which intends to perform some action. In languages like C# or Java, we have control structures for decision making , branching etc.. as statements rather than expressions.

The following snippet shows a classic “If -Else” statement in C#.

image

However, this can be simplified and curly braces are not mandatory here.

image

But I cannot write the following in C#. This is because I cannot return a statement where a function is supposed to return an “int”.

image

Similar stuff can be done in C# with a ternary operator as shown below:

image

But as the conditional statement becomes complex, usage of a ternary operator is difficult and makes the code clumsy and kludgy.

While playing around with Kotlin, I found that control structures like “If” , “When ( switch in C# or Java)” are expressions instead of statements and evaluates to a value. So, I can easily write the following.

image

This works as a simple alternative to the ternary operator. In Kotlin, there is no ternary operator as we don’t need any. But if-else expressions can be complex with multiple expressions/statements within it.In that case the last expression will be the “value” of that parent if/else expression as shown below.

image

Nested If-Else, If-Else-If expressions will also work in the same logic.

Kotlin, also has statement blocks enclosed within curly braces and the following “If” block without an “Else” is treated as a statement.

image