Kotlin – for, while, if, when

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
 List<String> names = new ArrayList<>();
        names.add("Laura");
        names.add("Catalin");
        names.add("George");

 for (String name : names) Log.e("Names", "My name is " + name);
  • using block
 List<String> names = new ArrayList<>();
        names.add("Laura");
        names.add("Catalin");
        names.add("George");

 for (String name : names) {
   Log.e("Names", "My name is " + name);
 }

Kotlin

  • inline
val names = listOf("Laura", "Catalin", "George")

for (name in names) Log.e("Names", "My name is $name")

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
val names = listOf("Laura", "Catalin", "George")

for (name in names) {
    Log.e("Names", "My name is $name")
}

Index-based loop

Java

List<String> names = new ArrayList<>();
        names.add("Laura");
        names.add("Catalin");
        names.add("George");

 for (int i = 0; i < names.size(); i++) {
      Log.e("Names", "My name is " + names.get(i));
 }

Kotlin

val names = listOf("Laura", "Catalin", "George")

for (i in names.indices) {
     Log.e("Names", "My name is ${names[i]}")
}

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

withIndex or Ranges loop

Java

List<String> names = new ArrayList<>();
names.add("Laura");
names.add("Catalin");
names.add("George");

for (int i = 0; i < names.size(); i++) {
    Log.e("Names", "The name at " + i + " is " + names.get(i));
}

Kotlin

val names = listOf("Laura", "Catalin", "George")

for ((i, value) in names.withIndex()) {
     Log.e("Names", "The name at $i is $value")
}

OR using Ranges (Kotlin)

for (i in 1..10) {
    print(i)
}

 

2. while loop

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

Both Java and Kotlin

var count = 1

while (count < 11) {
    ...
    count++
}

 

3. if expression

Traditional usage

Java

int a = 1;

if (a < 0) {
    Log.e("Log", "a is negative");
} else {
    Log.e("Log", "a is positive");
}

Kotlin

val a = 1

if (a < 0) {
   Log.e("Log", "a is negative")
} else {
   Log.e("Log", "a is positive")
}

As an expression (inline if)

Java

 int a = 1;
 String s = (a < 0) ? "a is negative" : "a is positive";

Kotlin

val a = 1
val s = if (a < 0) "a is negative" else "a is positive"

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
val a = 1
val b = 2

val message = if (a < b) {
    "a is min"
} else {
    "b is min"
}

Log.e("Log", "message = $message")

The output for the above code will be:

E/Log: message = a is min
  • 2 statements or more
 val a = 1
 val b = 2
       
 val message = if (a < b) {
     Log.e("Log", "a is min")
     a
 } else {
     Log.e("Log", "b is min")
     b
}

Log.e("Log", "min = $message")

The output of the above code is this:

 E/Log: a is min
 E/Log: min = 1

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

int a = 1;
String month;

switch (a) {
    case 1:
       month= "January";
       break;
    case 2:
       month= "February";
       break;
    default:
       month= "this month is missing";
}

Log.e("Log", "month = " + month);

Kotlin

val a = 1
val month: String

when (a) {
   1 -> month = "January"
   2 -> month = "February"
   else -> { // equivalent of "default" in Java. Note that it can be written as a block too!
      month = "this month is missing"
    }
}

Log.e("Log", "month = $month")

The output is:

E/Log: message = a is 1

Many cases that should be handled in the same way

Java

int a = 1;
String message;

switch (a) {
     case 1:
     case 2:
         message = "first 2 months";
         break;
    case 3:
        message = "March";
        break;
    default:
         message = "a is neither 1 nor 2";
}

Log.e("Log", "message = " + message);

Kotlin

val a = 1
val month: String

when (a) {
     1, 2 -> month = "first 2 months"
     3 -> month = "March"
     else -> { // equivalent of "default" in Java. Note that is written as a block!
          month = "this month is missing"
     }
}

Log.e("Log", "month = $month")

The output is:

E/Log: month = first 2 months

Arbitrary expressions (not only constants)

Java

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

Kotlin

val a = 1
val month: String

when (a) {
    1, 2 -> month = "first 2 months"
    getInt(3) -> month = "March"
    else -> { // equivalent of "default" in Java. Note that is written as a block!
         month = "this month is missing"
    }
}

Log.e("Log", "month = $month")
}
    
fun getInt(x: Int): Int {
   return x
}

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

Java

NONE

Kotlin

val a = 3
val month: String

 when (a) {
     in 1..3 -> month = "first trimester"
     in 3..6 -> month = "second trimester"
     !in 1..12 -> month = "outside of range"
     else -> { // equivalent of "default" in Java. Note that is written as a block!
          month = "this month is missing"
     }
}

        Log.e("Log", "month = $month")

The output is this:

E/Log: month = first trimester

 

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

Java

NONE

Kotlin

 val a = 3

fun isInt (a: Any) = when (a) {
    is Int -> "a is Int"
    else -> "is not an Int"
}

Log.e("Log", "message = ${isInt(a)}")

Output is:

E/Log: message = a is Int

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

val a = 0
val message: String

when {
   a > 0 -> message = "a is positive"
   a < 0 -> message = "a is negative"
   else ->  message = "a is equal to 0"
}

Log.e("Log", "message = $message")

The output is:

E/Log: message = a is equal to 0

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

 

 

, , , , , , , , , , ,
Previous Post
Kotlin – How to pass function as parameter
Next Post
Kotlin Common Questions

Related Posts

Menu