Skip to content

Kotlin If, When and While

Maria Maged M edited this page Apr 12, 2020 · 4 revisions

Kotlin - If, When and While

  • if is nearly ubiquitous in computer programming.
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 Java syntax.
Ruby
if(i > 10) 
	# Do something.
else
	# Do something.
end	
Kotlin
val i = 3
if(i > 10) {
	println("Something")
}
else {
	println("Something else")
}
  1. For single-line conditional work, you can skip the braces.
val i = 3
if(i > 10) println("Something") else println("Something else")
  1. It 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")

When

when is distinctive.

when is powerful.

when is used a lot in Kotlin programming.

What We Do Elsewhere

  • The closest analogy to when in Java is the switch statement.
  • Here, depending on the value of foo , we evaluate one set of statement that follows the matching case (or the default statements, if there are no matches).
switch(foo) {
case 1:
	  // Do something.
	  break;
case 2: 
	  // Do something else.
	  break;
default:
	  // Like, whatever.
}
  • Javascript also has a switch, with same syntax as Java.
  • Ruby uses case, and it is the closest of the three in terms of matching the power of when.
case foo
	when 1 
		# Do something.
	when 2
		# Do something else.
    else
	    # Like, whatever.
end

The Basic Use of when

The most commonly-seen of when looks like a Java/ JavaScript switch or Ruby case, when you supply a value for comparison and set up different branch conditions to test against that value:

val i = 3

when(i)  {
	1 -> println("Something")
	2 -> println("Something else")
	else -> println("And now for something completely different")
}
  • Each branch has a value.
  • That is compared to an input.
     
  • The first match has its statement or block evaluated, and everything else is skipped.
    • If there are no matches, the else statement or block is evaluated.
  • The -> separates the branch comparison to the stuff that should be executed if that branch comparison is met.

In this case, the output is:

And now for something completely different.

  • Anything that can be compared using equality (==) can be used.
val things = "foo"

when (thingy) {
	"foo" -> println("Something")
	"bar" -> println("Something else")
	else -> println("And now for something completely different")
}
  • However, you cannot mix types, unless *== happens to work to compare them.
  • This, for example, fails with a compiler error, pointing out that Int and String are incompatible types:
val things = "foo"

when(things) {
	"foo" -> println("Something.")
	2 -> println("Something else.")
	else -> println("And now for something completely different")
}

Clone this wiki locally