Kotlin – for, while, if, when

Control flow: for, while, if, when

This post is for beginners who want to start learning Kotlin language and already know Java. We will show simple examples of for, while, if, when in both languages, in parallel, for an easier understanding. We will use Log.e in order to print string messages, as from our point of view, is easier to read them in the Logcat.

1. for loop

Enhanced For-Loop

Java

  • inline

  • using block

Kotlin

  • inline

Notice that in Kotlin we used a “$” symbol in order to obtain the value of name variable. This is called a template expression.

  • using block

Index-based loop

Java

Kotlin

Notice that here, we used beside “$” symbol, curly braces “{“. This was necessary because names[i] is an expression.

withIndex or Ranges loop

Java

Kotlin

OR using Ranges (Kotlin)

 

2. while loop

The while loop in Kotlin is the same as the while loop in Java.

Both Java and Kotlin

 

3. if expression

Traditional usage

Java

Kotlin

As an expression (inline if)

Java

Kotlin

In both Java and Kotlin, if we use inline if, the “else” branch is required.

As an expression with blocks

Java 

NONE

Kotlin

  • 1 statement

The output for the above code will be:

  • 2 statements or more

The output of the above code is this:

What happens in this case? Well, a is indeed lower than b, so the code from the if branch will be executed. First, it will log the “a is min” message, and then a value will be assigned to “message” variable and the latest Log.e will log the message “min = 1” because a = 1.

As the official documentation states: ” if branches can be blocks, and the last expression is the value of a block”.

4. when expression

when expression in Kotlin is the equivalent of switch in Java.

General form

Java

Kotlin

The output is:

Many cases that should be handled in the same way

Java

Kotlin

The output is:

Arbitrary expressions (not only constants)

Java

In Java we can’t use arbitrary expressions. Constant expressions are required.

Kotlin

Check a value for being in or !in a range or a collection

Java

NONE

Kotlin

The output is this:

 

Check that a value is or !is of a particular type

Java

NONE

Kotlin

Output is:

Notice that in this scenario we assigned the value of when expression directly to the isInt function (method). This is one of the shorter ways of writing a function.

Replacement for an ifelse if chain

Java

NONE

Kotlin

The output is:

Note that in this scenario, when expression is followed directly by a curly brace “{“.