In this tutorial, we’ll be covering an important aspect of programming, namely Kotlin Control Flow statements.
We’ll look into the if
else
, range
, for
, while
, when
repeat
, continue
break
keywords that form the core of any programming language code.
Let’s get started with each of these operators by creating a Kotlin project in our IntelliJ Idea.
Kotlin if else
In Kotlin, if else operators behave the same way as it does in Java.
if
executes a certain section of code if the condition is true. It can have an optional else
clause.
Following code is from the Test.kt class in our IntelliJ Project.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun main(args: Array<String>) { var a = 4 var b = 5 var max = a if (a < b) max = b if (a > b) { max = a } else { max = b } println("a is $a b is $b max is $max") } |
In Kotlin, if else can be used as expressions too in order to return a value.
1 2 3 4 5 6 7 |
a = 5 b = 4 //if else returns a value in Kotlin max = if (a > b) a else b print("a is $a b is $b max is $max") |
This way Kotlin eliminates the use of ternary operator by using if else as expressions.
In another view, the last statement present in an if-else condition is returned as the value.
The below example demonstrates the same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
max = if(a>b) { println("a is greater than b") println("max is a") a } else{ println("b is greater than a") println("max is b") b } println("max is $max") //Following is printed on the log console. a is greater than b max is a max is 5 |
Kotlin for loop
The syntax of for loop in Kotlin is different from the one in Java.
For loop is used to iterate over a list of items based on certain conditions.
Following is the implementation of for loops in Kotlin to print numbers 0 to 5.
1 2 3 4 5 |
for (i in 0..5) { print(i) } |
Few inferences from the above syntax are listed below:
- Kotlin saves us from declaring the type of
i
- The lower and upper (including) limits are be defined on either side of
..
operator. in
keyword is used to iterate over the range.
Another case for you, where we iterate over an array using for-in
loop.
1 2 3 4 5 6 7 8 9 10 |
val items = listOf(10, 20, 30, 40) for (i in items) println("value is $i") //Following is printed to the console. value is 10 value is 20 value is 30 value is 40 |
To print the index of the elements, we invoke the indices
method on the arrays.
1 2 3 4 5 6 7 8 9 10 |
val items = listOf(10, 20, 30, 40) for (i in items.indices) println("value is $i") //Following is printed to the console: value is 0 value is 1 value is 2 value is 3 |
To access the index and value of the element in the iteration, withIndex()
function is used.
1 2 3 4 5 6 7 8 9 10 |
val items = listOf(10, 20, 30, 40) for ((i,e) in items.withIndex()) println("the index is $i and the element is $e") //Following is printed on the console: the index is 0 and the element is 10 the index is 1 and the element is 20 the index is 2 and the element is 30 the index is 3 and the element is 40 |
Kotlin forEach loop
ForEach loop repeats a set of statements for each iterable as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
(2..5).forEach{ println(it) } //or (2..5).forEach{ i -> println(i) } //Following is printed on the console: 2 3 4 5 |
it
is the default iterable variable that holds the value of the current iterator.
In the second case, we’d use our custom variable.
Kotlin Range
We’ve seen in the above sections that ..
operators represents a range.
1 2 3 4 5 6 7 8 9 |
(2..4).forEach{ println(it) } //Following gets printed on the console: 2 3 4 |
To check whether an element exists or doesn’t exist in a range we use the in
and !in
keywords as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var x = 5 if(x in 1..10) { print("x exists in range") //this gets printed } else{ print("x does not exist in range") } x = 15 if(x !in 1..10) { print("x does not exist in range") //this gets printed } else{ print("x does exist in range") } |
And the following should work the same way. Right?
1 2 3 4 5 6 7 8 9 10 11 12 |
var x = 5 if(x in 10..1) { print("x exists in range") } else{ print("x does not exist in range") //Ironically, this gets printed. } for (i in 5..0) print(i) //prints nothing |
NO.
The Range ..
can’t be used in the reverse order.
This is where we use the downTo
keyword.
The below code would work:
1 2 3 4 5 6 7 8 9 10 11 12 |
var x = 5 if(x in 10 downTo 1) { print("x exists in range") //this gets printed } else{ print("x does not exist in range") } for (i in 5 downTo 0) print(i) //543210 |
To exclude the last element from the range we use the keyword until
.
1 2 3 4 5 6 |
for (i in 1 until 4) { print(i) } //prints 123 |
To traverse the range in steps we use the keyword step
.
1 2 3 4 |
for (i in 1..5 step 3) print(i) // prints 14 for (i in 4 downTo 1 step 2) print(i) // prints 42 |
Kotlin while loop
while
and do-while
loops in Kotlin behave the same way as they do in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var i = 0 do { i+=5 println("Value of i is $i") //prints 5 } while(i<1) i=0 while(i<=5) { print(i) i++ } //prints 012345 |
Kotlin break and continue
break
is used to exit the loop there and then.
continue
is used to go to the next iteration of the loop.
Kotlin gives us the luxury to attach a label to the break and continue statements to indicate the loop on which their actions are triggered as shown below.
1 2 3 4 5 6 7 8 9 10 11 |
customLabel@ for(y in 10 downTo 5) { // applying the custom label if(y == 6) { print("x is $y breaking here") break@customLabel //specifing the label } else { print("continue to next iteration") continue@customLabel } } |
Kotlin repeat and when
repeat
allows us to execute the statements in the loop N number of times(where N is the number specified as the argument).
The following code snippet would print the group of statements 3 times.
1 2 3 4 5 6 |
repeat(3) { println("Hello World!") println("Kotlin Control Flow") } |
when
in Kotlin is equivalent to switch
in other languages, though with a different syntax and more power!
A basic example of when
operator is given below.
1 2 3 4 5 6 7 8 9 10 |
var num = 10 when (num) { 0 -> print("value is 0") 5 -> print("value is 5") else -> { print("value is neither 0 nor 5") //this gets printed. } } |
The when
operator matches the argument with all the branches. If it matches with none, the else
statement is printed. The else
statement is similar to default
in switch.
when
operator can be used to return values too, similar to if else.
1 2 3 4 5 6 7 8 9 |
var valueLessThan100 = when(101){ in 1 until 101 -> true else -> { false } } print(valueLessThan100) //false |
Going further, we can use Any type to check the branch as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun month(month: Any) { when(month) { 1 -> print("January") 2-> print("February") "MAR" -> print("March") else -> { print("Any other month or it is invalid. when operator takes generic type Any") } } } month(1) //"January" month("MAR") //"March" |
Kotlin Control Flow Statements Example
Summing up the control flow in our Kotlin project, this is how our Kotlin class file looks:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
fun main(args: Array<String>) { var a = 4 var b = 5 var max = a if (a < b) max = b if (a > b) { max = a } else { max = b } println("a is $a b is $b max is $max") a = 5 b = 4 //if else returns a value in Kotlin max = if (a > b) a else b println("a is $a b is $b max is $max") max = if(a>b) { println("a is greater than b") println("max is a") a } else{ println("b is greater than a") println("max is b") b } println("max is $max") val items = listOf(10, 20, 30, 40) for ((i,e) in items.withIndex()) println("index is $i and element is $e") (2..5).forEach{ print(it) } var x = 5 if(x in 10 downTo 1) { print("x exists in range") } else{ print("x does not exist in range") } var i = 0 do { i+=5 println("Value of i is $i") } while(i<1) i=0 while(i<=5) { print(i) i++ } customLabel@ for(y in 10 downTo 5) { // appling the custom label if(y == 6) { print("x is $y breaking here") break@customLabel //specifing the label } else { print("continue to next iteration") continue@customLabel } } repeat(3) { println("Hello World!") println("Kotlin Control Flow") } var num = 10 when (num) { 0 -> print("value is 0") 5 -> print("value is 5") else -> { print("value is neither 0 nor 5") } } var valueLessThan100 = when(101){ in 1 until 101 -> true else -> { false } } print(valueLessThan100) //false month(1) month("MAR") } fun month(month: Any) { when(month) { 1 -> print("January") 2-> print("February") "MAR" -> print("March") else -> { print("Any other month or it is invalid. when operator takes generic type Any") } } } |
This brings an end to this tutorial
References: Kotlin Official Doc, Range API Doc