Basics of Kotlin - Part 3
Tags: android, computerscience, programming, kotlin
Published: 2021-04-24 10:36:38

In the last article, we learnt about some basic concepts of Kotlin like type casting, operators, how to take input and comments. Before reading this article make sure you had read the last article <a href="https://dev.to/csj5483/basics-of-kotlin-part-2-51o3">Basics of Kotlin- Part 2</a>. Let's learn more about Kotlin.

<h4>if expression:</h4>
In Kotlin, <b>if</b> is an expression which returns a value. It is used to control the flow of the program structure.
```
For example:
var a=7;
if(a%2==0){
    print("even number")
}
```
In the above code snippet, the reminder of a with 2 is not equal to 0 so it will not execute the code of <b>if</b> block and will not give any output.

<h4>if-else:</h4>
In <b>if-else</b>, if the condition of <b>if</b> expression is true then it will execute the code of the <b>if</b> block otherwise it will execute the code of <b>else</b> block.
```
var a=7;
 if(a%2==0){
     print("even number")
 }
 else{
    print("odd number")
 }
Output : odd number
```
In the above code snippet, the reminder of a with 2 is not equal to 0 so it will not execute the code of <b>if</b> block and will execute the code of <b>else</b> block.

<h4>if-else ladder:</h4>
In this, we will check multiple conditions.
```
var num=7;
 if(num>0){
    print("positive number")
 }
 else if(num<0){
    print("negative number")
 }
 else{
    print("zero")
 }
Output : positive number
```

<h4>Nested if:</h4>
In this, we have conditions inside the block of a condition.
```
val num1=10
val num2=20
val num3=15
if(num1>num2){
   if(num1>num3){
        print("num1 is largest")
   }
   else{
      print("num3 is largest")
   }
}
else if(num2 > num3){  
   print("num2 is largest") 
}
else{  
   print("num3 is largest")
}
Output :
num2 is largest
```
The above code snippet will print the largest number of 3 numbers.

<h4>when expression:</h4>
<b>when</b> expression in Kotlin is similar to <b>switch</b> statement in Java/C++. It is basically a conditional operator in which multiple conditions can be applied on a particular variable. <b>when</b> operator matches the variable value against the branch conditions. If it is satisfying the branch condition then it will execute the statement inside that scope.
```
val num=3
    when(num){
        1 -> println("One")  
        2 -> println("Two")  
        3 -> println("Three")  
        4 -> println("Four")  
        5 -> println("Five")  
        else -> println("invalid number")  
    }
Output :
Three
```
We can have multiple statements enclosed within a block of condition.
```
val num=1
when(num){
     1->{
       println("first")
       println("day")
    }
    else->print("not first")
}
Output :
first
day
```
We can use multiple branches of condition separated with a comma. It is used, when we need to run the same logic for multiple choices.
```
var num=4
when(num){
  0,2,4,6,8->println("even")
  1,3,5,7,9->println("odd")
  else->println("number greater than 9")
}
Output : even
```
The when expression also checks the ranges of input provided in <b>when</b> condition. A range is created using .. (double dot) operator. The in operator is used to check if a value belongs to a range.
```
var num=8
when(num){
   in 1..5->print("num is from 1 to 5")
   in 6..10->print("num is from 6 to 10")
   else->print("num is greater than 10")
}
Output : num is from 6 to 10
```
<h4>for loop:</h4>
for loop is used to iterate through any kind of data structure. It iterates through arrays, ranges, collections, or anything which is provided for iteration. This is equivalent to the `foreach` loop in languages like Java, C#.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xheucz2qhoroj6917n0j.png)
```
var array=arrayOf(1,2,3,4,5)
for(item in array)
  println(item)
Output :
1
2
3
4
5
```
The above code snippet will print each item of the array.

To iterate over a range of numbers, we can use a range expression:
```
for( i in 1..3)
    println(i)
Output :
1
2
3
```
We can modify the for loop according to our requirements. For example, if we want to print the first five even number, then we can use the following code:
```
for(i in 2 .. 10 step 2)
    println(i)
Output :
2
4
6
8
10
```
Here step is the increment in the counter variable.

<h4>while loop:</h4>
while loop will continuously execute the body code while their condition is satisfied.
```
var num=5
 while(num>0){
      println(num)
      num--
 }
Output : 
5
4
3
2
1
```

<h4>do-while loop:</h4>
do-while loop will continuously execute the body code while their condition is satisfied.
```
var num=10
do{
  println(num)
  num--
}while(num>5)
Output :
10
9
8
7
6
```

The difference between while and do-while is:

> `while` checks the condition and, if it's satisfied, executes the body and then returns to the condition check.

> `do-while` executes the body and then checks the condition. If it's satisfied, the loop repeats. So, the body of do-while executes at least once regardless of the condition.


<h3>Return and Jump:</h3>
Kotlin has three jump expressions.
<ul><li>
<b>return</b> by default returns from the nearest enclosing function or anonymous function.</li>
<li><b>break</b> terminates the nearest enclosing loop.</li>
<li><b>continue</b> proceeds to the next step of the nearest enclosing loop.</li>
</ul>
<b>return:</b>
It is a keyword that returns some value to the calling function from the called function.
```
fun main() {
    var x=5
    println(square(x))
 
}
fun square(x:Int):Int{
    return x*x
}
Output : 25
```
In the above code, the square function will return the square value of the variable.

<b>break:</b>
break is used to terminate the controller flow. In the below example, for loop will terminate its loop when <b>if</b> condition executes break expression.
```
for(i in 1..5){
      if(i==4){
          break
      }
      println(i)
}
Output :
1
2
3
```
As we can see in the above code when i==4 become true loop gets terminated and we don't get any output after that.

<b>continue:</b>
continue is used to skip the current iteration of the loop and jumps the control to the end of the loop for the next iteration. It is generally used with if-else to skip the current iteration of the loop for a specific condition.
```
for(i in 1..5){
        println("$i before continue")
        if(i==4)
         continue
        println("$i after continue") 
}
Output:
1 before continue
1 after continue
2 before continue
2 after continue 
3 before continue 
3 after continue 
4 before continue 
5 before continue 
5 after continue
```
As we can see for i=4 after continue statement doesn't get printed because continue had escaped the remaining code and the control goes to the end of the loop for the next iteration.

That's it for this article. We will continue in the next article.

Happy Learning!