If, When, and While

Branching and looping are common operations in most programming languages. Most languages have some concept of if (branch based on a condition) and while (loop based on a condition). Kotlin has its takes on those control structures, plus a when structure that is a bit reminiscent of things like Java’s switch structure.

So, let’s take a look at if, when, and while, and see how Kotlin handles them the same as — and in some cases, differently than — other languages.

If

if is nearly ubiquitous in computer programming, whether that is Java:

if (i>10) {
  // do something
}
else {
  // do something else
}

…JavaScript:

if (i>10) {
  // do something
}
else {
  // do something else
}

// yes, it is the same as the Java syntax

…or Ruby:

if (i>10)
  # do something
else
  # do something else
end

On the surface, a Kotlin if works the same way:

  val i = 3

  if (i > 10) {
    println("something")
  }
  else {
    println("something else")
  }

As with most languages, the else clause is optional, if you do not have anything special that you want to do in that situation:

  val i = 3

  if (i > 10) {
    println("something")
  }

  println("the if is done")

For single-line conditional work, you can skip the braces:

  val i = 3

  if (i>10) println("something") else println("something else")

if also supports else if in addition to a simple else:

  val i = 3

  if (i > 10) {
    println("something")
  }
  else if (i > 2) {
    println("something else")
  }
  else {
    println("and now for something completely different")
  }

However, as you will see in the next section, the convention in Kotlin development is to use when instead of if for such scenarios.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.