Kotlin Conditionals


Conditionals allow us to define rules for when a code should be executed. This language feature is called control flow and it allows you to describe the conditions for when specific portions of your program should run.

There are 2 main conditionals available in Kotlin:

if/else

There are two branches: if branch and else branch. We use the word branch because the flow of your code execution will branch depending on whether your specified condition is met or not.

var score = 72
if (score > 75)
  println("Pass with distinction")
else
  println("No distinction")

We can use if/else code when we have multiple conditions like this

var score = 72
if(score > 75)
  println("First division with distinction")
else if(score > 60)
  println("First division")
else if(score > 50)
  println("Second division")
else if(score > 30)
  println("Third division")
else
  println("Fail")

/*
Output here will be "First division"
*/

The order of the conditions can matter in if/else flow. This means if I change the order of conditions in the above example, the output will change.

var score = 72
if(score > 75)
  println("First division with distinction")
else if(score > 50) // Moved from third to second position
  println("Second division")
else if(score > 60) // Moved from second to third position
  println("First division")
else if(score > 30)
  println("Third division")
else
  println("Fail")

/*
Output here will be "Second division"
*/

when

when checks the value of the argument in parentheses () against each of the values on the left hand side of -> (arrow) operator and when it matches, it executes the code on the right hand side of the arrow operator.

By default, when behaves as though there were a == (equality) operator between the argument you provide in parentheses and the conditions you specify in the curly braces.

when provides a more concise syntax and is an especially good fit for conditionals with three or more branches.

var language = "Kotlin"
when(language){
  "Java" -> println("Code is in Java language")
  "Kotlin" -> println("Code is in Kotlin language")
  "Python" -> println("Code is in Python language")
  "Scala" -> println("Code is in Scala language")

How is when different from switch in Java

  1. In Java, you have to use break or return if you want to stop operating inside the switch branch else unexpected results will come. In Kotlin, if a condition is satisfied, the result of the corresponding branch is returned.
  2. Sometimes we use conditionals to check type hierarchy of a variable. Kotlin uses is to check whether an argument is of specific type instead of instance of as in Java.
  3. In java, you cast the variable type even after checking instance of whereas, in Kotlin, you simply access its members as it was of right type.

Example to explain the last two points comparing the Java and Kotlin code

Java

switch(user){
  instance of Student -> ((Student)user).isPresent()
  instance of Teacher -> ((Teacher)user).isPresent()
}

Kotlin

when(user){
  is Student -> user.isPresent()
  is Teacher -> user.isPresent()
}

In Kotlin you can even get the argument from another expression and pass it in the parameter like this:

when(val user = getUser()){
  is Student -> user.isPresent()
  is Teacher -> user.isPresent()
}

when can also be executed without arguments. In this case you can put any Boolean expression as the branch condition. If it is satisfied, the the corresponding branch code is executed.

when {
  score > 75 -> println("First division with distinction")
  score < 75 && score > 60 -> println("First division")
  score < 60 && score > 50) -> println("Second division")
  score < 50 && score > 30 -> println("Third division")
  else -> println("Fail")
}


Conditional expressions

In Kotlin, you can assign the output of if/else or when to a variable and can use it later.

val language = "Kotlin"
val result = when(language){
  "Java" -> "Code is in Java language"
  "Kotlin" -> "Code is in Kotlin language"
  "Python" -> "Code is in Python language"
  "Scala" -> "Code is in Scala language"
  else -> "No language specified"
}
println(result)

If an if/else or a when branch has multiple statements, the last line is returned as output to the variable.

when expression works similar to an if/else expression in that you define conditions and branches that are executed if a condition is true. when is different in that it scopes the left hand side of the condition automatically to whatever you provide as an argument to when, meaning in the above example scope of result variable will be same as scope of language variable.


Operators

In order to write multiple conditions in if/else or when, we need multiple comparison and logical operators. Here’s a list of operators and their description.

Comparison Operators
<    Evaluates whether the value on the left is less than the value on the right
<=   Evaluates whether the value on the left is less or equal to than the value on the right
>    Evaluates whether the value on the left is greater than the value on the right
>=   Evaluates whether the value on the left is greater than or equal to the value on the right
==   Evaluates whether the value on the left is equal to the value on the right
!=   Evaluates whether the value on the left is equal to the value on the right
===  Evaluates whether the two instances point to the same reference.
!==  Evaluates whether the two instances do not point to the same reference.
Logical Operators
&&   Logical "and" : true if and only if both are true (false otherwise)
||   Logical "or" : true if either is true (false only if both are false)
!    Logical not : true becomes false and false becomes true

Note: When operators are combined, there is an order of precedence that determines what order they are evaluated in and operators with the same precedence are applied from left to right.

Order of precedence from highest to lowest

!
< , ≤ , > , ≥ 
==( Structural equality) , != (non-equality)
&&
||


Ranges

Kotlin provides ranges to represent a linear series of values. The .. operator signals a range. A range includes all values from the value on the left of the .. operator to the value on the right, so 1..5 includes 1, 2, 3, 4, 5.

You can use the “in” keyword to check whether a value is within a range. You can also use “!in” to check whether a value is not in the range.

Using ranges in a conditional solves the else if ordering issue. With ranges, your branches can be in any order and the code will evaluate the same.

var result = when {
  score > 75 -> "First division with distinction"
  score in 60..74 -> "First division"
  score in 50..59 -> "Second division"
  score in 30..49 -> "Third division"
  else -> "Fail"
}

println(result)

You can define a range of any comparable elements.

val intRange: IntRange = 1..9
val anotherIntRange: IntRange = 1 until 10
val charRange: CharRange = 'a'..'z'
val stringRange: ClosedRange<String> = "ab".."az"
val dateRange: ClosedRange<MyDate> = startDate..endDate
val doubleRange: OpenEndRange<Double> = 1.12..10.23

A few pointers:

  1. ClosedRange represents a range of values where both lower and upper bounds are included in the range.
  2. OpenEndRange represents a range of values where the upper bound is not included in the range.
  3. The strings are compared lexicographically by default or in other words by the alphabetical order. That means, first letters are compared and only if they are same the rest letters are compared.
println("Kotlin" in "Java".."Scala") // returns true
println("Kotlin in setOf("Java", "Scala") // returns false

4. You can define a range of any custom classes as well. You class has to implement the Comparable Interface and you have to implement the compareTo function.

There are several other functions for creating ranges. We will see some more in the future articles.


That’s it for this article. Hope it was helpful! If you like it, please hit like.

Other articles of this series:


One response to “Kotlin Conditionals”

Leave a reply to Kucia Kodes Cancel reply