Kotlin provide various kind of expression and loops which help us to control the flow of our program.Here are some expression and loops which kotlin provide.

Kotlin if Expression

In Kotlin, if is a kind of conditional expression which returns a value. this loop is used for control the program structure’s flow. There is 3 type of if expression in Kotlin.

  • if-else expression
  • if-else if-else ladder expression
  • nested if expression

Traditional if Statement

Syntax of traditional if statement

1. if(condation){  
2. //your code   
3. }  

Syntax of traditional if else statement

1. if(condation){  
2. //your code  
3. }  
4. else{  
5. //your code   
6. } 

Kotlin if-else Expression

As if is an expression it’s not used as standalone, it’s used with if-else expression and also the results of an if-else expression is assign into a variable.

Syntax of if-else expression

1. val returnValue = if (condation) {  
2.      //your code   
3.     } else {  
4.      // your code   
5.     }  
6.     println(returnValue)  

Kotlin if-else Expression Example

Here is an example of if-else expression.

1. fun main(args: Array<String>) {  
2.         val number1 = 5  
3.         val number2 =10  
4.         val result = if (num1 > num2) {  
5.             "$number1 is greater than $num2"  
6.         } else {  
7.             "$number1 is smaller than $num2"  
8.         }  
9.         println(result)  
10. }  

Kotlin if-else if-else Ladder Expression

example of if-else if-else ladder expression.


1. fun main(args: Array<String>) {  
2.     val number = 5  
3.     val result = if (number > 0){  
4.         "$number is positive"  
5.     }else if(number < 0){  
6.         "$number is negative"  
7.     }else{  
8.         "$number is zero"  
9.     }  
10.     println(result)  
11. } 

Output:

5 is positive

Kotlin Nested if Expression

Let’s see an example of nested if expression.

1. fun main(args: Array<String>) {  
2.     val number1 = 25  
3.     val number2 = 20  
4.     val number3 = 30  
5.     val result = if (number1 > number2){  
6.   
7.         val max = if(number1 > number3){  
8.             number1  
9.         }else{  
10.             number3  
11.         }  
12.         "body of if "+max  
13.     }else if(number2 > number3){  
14.         "body of else if"+number2  
15.     }else{  
16.         "body of else "+number3  
17.     }  
18.     println("$result")  
19. }

Output

body of if 30

Kotlin when Expression

In kotlin, when expression is a conditional expression which returns the value. It is replacement of switch statement and  works as a switch statement of other language (Java, C++, C).

Using when as an Expression

Let’s see a simple example of when expression.

1. fun main(args: Array<String>){  
2.     var number = 4  
3.     var numberProvided = when(number) {  
4.         1 -> "One"  
5.         2 -> "Two"  
6.         3 -> "Three"  
7.         4 -> "Four"  
8.         5 -> "Five"  
9.         else -> "invalid number"  
10.     }  
11.     println("You provide $numberProvided")  
12. }

Output

You provide Four

Using when Without Expression

It is not mandatory to use when with an expression, we can be use as normally as we used in other language.

For Example

1. fun main(args: Array<String>){  
2.   
3.     var number = 4  
4.     when(number) {  
5.         1 -> println("One")  
6.         2 -> println("Two")  
7.         3 -> println("Three")  
8.         4 -> println("Four")  
9.         5 -> println("Five")  
10.         else -> println("invalid number")  
11.     }   
12. }  

Output

Four

Multiple Statement of when Using Braces

We can also use multiple statement enclosed within block of condition in when expression.

For Example

1. fun main(args: Array<String>){  
2.     var number = 1  
3.     when(number) {  
4.         1 -> {  
5.             println("Monday")  
6.             println("First day of the week")  
7.         }  
8.         7 -> println("Sunday")  
9.         else -> println("Other days")  
10.     }  
11. }

Output

Monday
First day of the week

Multiple branches of when

We can also use multiple branches of condition which is separated with a comma. we mostly use it, when we have to run a same logic for multiple choices.

1. fun main(args: Array<String>){  
2.     var number = 8  
3.     when(number) {  
4.         3, 4, 5, 6 ->  
5.             println("It is summer season")  
6.         7, 8, 9 ->  
7.             println("It is rainy season")  
8.         10, 11 ->  
9.             println("It is autumn season")  
10.         12, 1, 2 ->  
11.             println("It is winter season")  
12.         else -> println("invalid input")  
13.     }  
14. }  

Output

It is rainy season

Using when in the range

The when expression have capability to check the ranges of input provided in when condition. A range is created in kotlin using .. (double dot) operator. The in operator is used to check if a value belongs to a range or no

For Example:

1. fun main(args: Array<String>){  
2.     var number = 7  
3.     when(number) {  
4.         in 1..5 -> println("Input is provided in the range 1 to 5")  
5.         in 6..10 -> println("Input is provided in the range 6 to 10")  
6.         else -> println("none of the above")  
7.     }  
8. } 

Output:

Input is provided in the range 6 to 10

Kotlin for Loop

Kotlin for loop is used to iterate a part of program many times. It iterates by the use of arrays, ranges, collections, or anything that provides for iterate. Kotlin for loop is similar to the foreach loop in languages like C#.

Syntax of for loop in Kotlin:

1. for (item in collection){  
2. //body of loop  
3. } 

Iterate through array

example of iterating the elements of array.

1. fun main(args : Array<String>) {  
2.     val marks = arrayOf(80,85,60,90,70)  
3.     for(item in marks){  
4.         println(item)  
5.     }  
6. }  

Output

80
85
60
90
70

 In for loop it is not necessary to enclose within curly braces {}  when the body of for loop contains only one single line of statement.

1. fun main(args : Array<String>) {  
2.     val marks = arrayOf(80,85,60,90,70)  
3.     for(item in marks)  
4.         println(item)  
5. }

example

1. fun main(args : Array<String>) {  
2.      
3.     val marks = arrayOf(80,85,60,90,70)  
4.     for(item in marks.indices)  
5.        println("marks[$item]: "+ marks[item])  
6. } 

Output:

marks[0]: 80
marks[1]: 85
marks[2]: 60
marks[3]: 90
marks[4]: 70

Iterate through range

example of iterating the elements of range.

1. fun main(args : Array<String>) {  
2.   
3.     print("for (i in 1..5) print(i) = ")  
4.     for (i in 1..5) print(i)  
5.     println()  
6.     print("for (i in 5..1) print(i) = ")  
7.     for (i in 5..1) print(i)  // prints nothing  
8.     println()  
9.     print("for (i in 7 downTo 1) print(i) = ")  
10.     for (i in 7 downTo 1) print(i)  
11.     println()  
12.     print("for (i in 7 downTo 2) print(i) = ")  
13.     for (i in 7 downTo 2) print(i)  
14.     println()  
15.     print("for (i in 1..7 step 2) print(i) = ")  
16.     for (i in 1..7 step 2) print(i)  
17.     println()  
18.     print("for (i in 7 downTo 1 step 2) print(i) = ")  
19.     for (i in 7 downTo 1 step 2) print(i)  
20. } 

Output:

for (i in 1..5) print(i) = 12345
for (i in 5..1) print(i) = 
for (i in 5 downTo 1) print(i) = 7654321
for (i in 5 downTo 2) print(i) = 765432
for (i in 1..5 step 2) print(i) = 1357
for (i in 5 downTo 1 step 2) print(i) = 7531

The while loop is used to iterate a part of program many time. It  executed the block of code until the condition has true. Kotlin while loop is equavalent to Java while loop.

Kotlin while Loop

Syntax

1. while(condition){  
2. //body of loop  
3. } 

Example of while Loop

1. fun main(args: Array<String>){  
2.     var i = 1  
3.     while (i<=5){  
4.         println(i)  
5.         i++  
6.     }  
7. }

Output

1
2
3
4
5

Kotlin Infinite while Loop

This while loop executes a block of code to infinite times, if while condition remain true.

For example:

1. fun main(args: Array<String>){  
2.         while (true){  
3.         println("infinite loop")  
4.         }  
5. } 

Output

infinite loop
infinite loop
infinite loop
.
.
.
.
infinite loop
infinite loop

 
infinite loop
infinite loop
infinite loop
infinite loop

Kotlin do-while Loop

The do-while loop is equavalent to while loop except one key difference. Do-while loop first execute the body of do block then it check the condition of while.As a do block of do-while loop executed first before checking the condition, do-while loop execute a minimum of once even the condition within while is false. Do-while loop’s while statement end with “;” (semicolon).

Syntax

1. do{  
2. //body of do block  
3. }  
4. while(condition); 

  Example of do -while loop

1. fun main(args: Array<String>){  
2.     var i = 1  
3.     do {  
4.         println(i)  
5.         i++  
6.     }  
7.     while (i<=5);  
8. } 

Output

1
2
3
4
5

Example of do -while loop even condition of while if false

here do-while loop execute at once time even the condition of while is false.checkout the example

1. fun main(args: Array<String>){  
2.     var i = 6  
3.     do {  
4.         println(i)  
5.         i++  
6.     }  
7.     while (i<=5);  
8. }  

Output

6

Kotlin Return and Jump

n Kotlin there are three jump expressions.These jump expressions are helpful for control the flow of program execution. These jump structures are:

  • break
  • continue
  • return

Break Expression

A break expression is used for target the nearest enclosing loop. It is mostly used with if-else condition.

For example:

1. for(..){  
2.        //body of for  
3.        if(checkCondition){  
4.            break;  
5.        }  
6. } 

Kotlin break example:

1. fun main(args: Array<String>) {  
2.     for (i in 1..5) {  
3.         if (i == 3) {  
4.             break  
5.         }  
6.         println(i)  
7.     }  
8. }  

Output:

1
2

In the above example, As we can see when the value of i became equal to 3 and matches the if condition(i==3) than the break expression execute and terminate for loop.

Kotlin continue Jump Structure

In kotlin continue statement is used to recall the loop. It keeps continue the current flow of the program and skips the remaining code at some specified condition.The continue statement within a nested loop only affects the inner loop as you can see in example given below.

For example

1. for(..){  
2.        //body of for above if  
3.        if(checkCondition){  
4.            continue  
5.        }  
6. //body of for below if  
7. } 

In the above example, for loop repeat its loop when if condition execute continue. The continue statement makes repetition of loop without executing the below code of if condition.

Kotlin continue example

1. fun main(args: Array<String>) {  
2.         for (i in 1..3) {  
3.             println("i = $i")  
4.             if (j == 2) {  
5.                 continue  
6.             }  
7.             println("this is below if")  
8.         }  
9. }  

Output

i = 1
this is below if
i = 2
i = 3
this is below if

You may also like...

0 Comments

No Comment.