Control Flow Statements in Kotlin

Control flow statement are nothing but logical statements which will choose the path of the to be executed.

    Conditional Statements

  • if
  • if..else
  • if..else..if
  • nested if
  • when
  • Loops

  • for
  • while
  • do-while
  • for loop & types
  • Ranges and Progressions
  • break and continue

invoke Operator in kotlin

if condition in kotlin

If statements are used as decision points to check a series of possible conditions, then take a decision to change the path of the program for each condition depending on the outcome.

In Kotlin, if statement is an expression, so expression do return values unlike statements.

In layman words : You want travel to a distance, you could either use train or car, normally what we do is , if the distance is 20 miles we take our car and go there but if the distance is more than 20 miles we take train and go to destination. In this example the distance is the deciding factor, so based on this deciding factor we will travel.

If condition takes the decision based on the expression given, if accepts a expression which would result either true or false

Following program takes decision based on the loan, it is a practical example.


fun main(args:Array<String>)
{
    // distance in miles
    var loan = "Educational Loan"
    if(loan == "Educational Loan")
    {
        println("Sorry, we don't provide loans")
    }
}			

In above code, if the loan is "Educational Loan" then expression resolves to true, then we want to print the message "Sorry, we don't provide loans".

Curly brackets are optional if you have only one line of code in side if block.


fun main(args:Array<String>)
{
    // distance in miles
    var loan = "Educational Loan"
    if(loan == "Educational Loan") println("Sorry, we don't provide loans")
}			

Sometimes we want to have other option to do something when the expression don't resolve to true.

if..else :

else is the optional block used to execute if the expression in the if doesn't resolve to true.

Either if block gets executed or else block, not both blocks gets executed and one block must get executed.


fun main(args:Array<String>)
{
    // distance in miles
    var loan = "Car Loan"
    if(loan == "Educational Loan")
    {
        println("Sorry, we don't provide loans")
    }else{
        println("We provide loan in 10 minutes")
    }
}			

if..else..if :

Sometimes we want to take decision in else block as well when we have more than one options, In such cases we can use if..else..if block.


fun main(args:Array<String>)
{
    // distance in miles
    var loan = "Car Loan"
    if(loan == "Educational Loan")
    {
        println("Sorry, we don't provide loans")
    }else if(loan == "Car Loan"){
        println("We 'CAR' Loan in 10 Minutes")
    }
}			

if..else..if..else :

We can add more if and else blocks in kotlin but one if block can have only one respective else block.


fun main(args:Array<String>)
{
    // distance in miles
    var loan = "Car Loan"
    if(loan == "Educational Loan")
    {
        println("Sorry, we don't provide Educational Loan")
    }else if(loan == "Agriculture Loan"){
        println("We donot provide Agriculture Loan")
    }else{
        println("We provide only luxury loans")
    }
}			

Nested if :

Sometime you have to take multiple decision based on the first decision you might get two paths to choose an you have to choose one in it , again you may need to choose one and then it goes on .

In such kind of situations, it is better to use nested if statements in kotlin, you can also have nested if statements in else block as well.


fun main(args:Array<String>)
{
    // distance in miles
    var loanBroadType = "Basic Loan"
    var loanSpcifictype = "Educational Loan"
    if(loanBroadType == "Basic Loan")
    {
        if(loanSpcifictype == "Educational Loan"){
            println("Sorry, we don't provide Educational Loan")
        }
    }else{
        if(loanSpcifictype == "car Loan"){
            println("yes, we provide Car loans")
        }
    }
}			

When construct in kotlin

If..else as expression to return a value

In other languages, if statement is used to take decision and it is a statement, but in kotlin if..else is a expression and it can return a value.

To return a value using the if..else, we must need to have else block otherwise kotlin will not know what value to assign when the conditional statement resolves into false. This is one of the way to avoid the Nulls.

If you don't provide else block kotlin will throw complier time exception. It is not mandatory to have else block when you don't return a value.


fun main(args:Array<String>)
{
    var loanBroadType:String
    var loanSpcifictype = "Educational Loan"
    loanBroadType = if(loanSpcifictype == "Educational Loan")
    {
        println("below will return value for if block")
        "Basic Loan" // this is return value
    }else{
        println("I am return value for else block")
        "Luxury loan" // this is return value
    }
    println(loanBroadType)
}			

May be, below example look familiar to you if you are from other languages.


fun main(args:Array<String>)
{
    var a:Int =3
    var b:Int =7
    var max:Int
    // might look like ternary operator
    max = if(a>b) a else b
    println(max)
}			

Yes, Ternary operator, and there is no ternary operator in Kotlin.

Member Functions in Kotlin

When construct

Kotlin's When expression takes decision based on the given input, unlike if..else, when statement could choose path from more than two paths in the program.

When expression is the replacement of switch statement from other languages like C, C++, and Java. It is concise and more powerful than switch statements.

when construct uses branches rather than case statements, when construct can be used as statement and expression as well.

    Types of When usage :
  • When with argument
  • When without argument

When with argument

Kotlin allows you to use any objects as the argument, but this other languages may allow only to use constants(number constants, string constants, enum constants).

We don't have to write the break; statement to terminate the branch, but it may cause issues in other languages but not in kotlin.


fun main(args:Array<String>)
{
    val language = "java"
    when(language){
        "java" -> println("Switch is used in Java")
        "kotlin" -> println("When is used in Kotlin")
        else -> println("You neither choose Java not Kotlin")
    }// 1 example ends here
    // second example for writing function
    val num = 3
    when(num){
        3 -> {
            println("sample for writing a block in when")
            println(3*3)
        }
        4 -> {
            println("sample for writing a block in when")
            println(4*4)
        }
        else -> println("Are you trying for square or square root")
    }// 2 example ends here
}		

When like Arbitrary expression :

We can use arbitrary expression in when construct to execute when something is true in the branch level. Else block is mandatory because kotlin doesn't know what to return when all conditions are evaluating to false.


fun main(args:Array<String>)
{
    val language = "java"
    var age= when(language){
        "java" -> "Old language"
        "kotlin" -> "New language"
        else -> "Not able to find age"
    }
	println(age)
}		

'in' in When construct :

We can use the 'in' operator to check whether given value is present in given data set or in collection.


fun main(args:Array<String>)
{
    val arr = listOf(9, 3, 5, 7)
    val targetValue = 50
    when(targetValue){
        in arr -> println("target value is in given list")
        in 10..100 ->println("target value is present in 10 to 100")
        else -> "Not able to find target value"
    }
}		

When construct with smart cast :

You can use the when construct along with smart cast, very important this while using smart cast along with when, you must pass the variable with "Any" type if you are having more than one smart cast branches inside.


fun main(args:Array<String>)
{
    val targetValue:Any = 50
    // result can have either length of string or square of number
    var result = when(targetValue){
        is Int -> {
            println("calculating square")
            targetValue * targetValue  // return value
        }
        is String -> {
            println("calculating length of string")
            targetValue.length // return value
        }
        else -> {
            println("on else block")
            0 // return value
        }
    }
    println(result)
}		

If you try to replace that targetValue declaration in above code like this, then you might see an error.

Error:(17, 12) Kotlin: Incompatible types: String and Int

val targetValue = 50		

When without argument

When without argument can be used as series of if..else conditions, if we don't provide a argument to when construct then we have to provide some condition at branch level.

Branches gets executed only when condition evaluates to true otherwise it moves to next branch and evaluates the condition and it goes on till some branch condition becomes true.

Only one branch will be executed in the when construct branches, in these cases else block is optional.

Kotlin is smart enough to execute the only the branch whose' condition resolve d to true.


fun main(args:Array<String>)
{
    val name:String = "karthiq"
    when{
        name.length < 5 -> println("Name has less than 5 letter")
        name.length > 5 -> println("Name has more than 5 letters")
        else -> println("name has 5 letters")
    }
}

Combine multiple when branches into one using comma :

You can combine multiple branches into one using comma in when construct. Combining multiple branches would be helpful when you need to run a common logic for multiple cases


var day = 3
when(dayOfWeek) {
    1, 2, 3, 4, 5 -> println("Working days")
    6, 7 -> println("Not working Days")
    else -> println("Provide valid day")
}			

Overload Compound Operators

Loops in Kotlin

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

A sequence of statements are executed until a specified/Given condition is true, or the loop is broken using break statement

This sequence of statements to be executed is kept inside the curly braces { } known as the Loop body, if there only one statement then we can write without {}.

After every execution of loop body, condition is verified, and if it is found to be true the loop body is executed again.

When the condition check returns false, the loop body is not executed.

There are Three types of Loops in Kotlin :

  • While
  • do-While
  • for

Depending on the position of control statement in the loop the control structure may be classified as either entry controlled loop or exit controlled loop.

For and while loop are entry controlled loop because the condition is checked on the entry and do - while loop is a exit controlled loops the condition is checked at end of the loop..

Returning function from function

While Loop in Kotlin

You use the keyword while, then a condition enclosed in parentheses, then a single statement, which is the thing which gets repeated as long as the condition is true.


// execute only if condition is true
while (condition) {
...
}		

If the body of the loop has to be more than one statement, enclose it in the curly brackets {}. This creates a compound statement, and the while will treat it as a single statement.

The condition can be any expression, from a single variable or constant, through a complex sequence of logical operators. Just be sure that condition evaluates to the boolean values true or false, or the compiler will signal a type error.

Kotlin is different from C, In C any non-zero integer value is considered true but kotlin throw error for it. So kotlin will not consider the numbers in place of condition


fun main(args:Array<String>)
{
    var i = 0
    while(i<10){
        println(i)
        i++ // i= i+1
    }
}		

throws annotation in Exceptions

do - while loop in kotlin

In a do…while loop, the statements in the body of the loop are executed once before the condition governing the loop is tested.

If the condition evaluates to true, the loop will iterate a second time executing the loop’s body again, otherwise the loop exists because the condition has become false.


do{
   //statements
} while (condition)		

As for a real-world example of this, consider the input of a PIN number when using a cash dispenser. The PIN must be entered once prior to testing so a do…while loop is a perfect choice, i.e.:


fun main(args:Array<String>)
{
    var actualPIN = "1212"
    var attempts = 0
    do{
        println("Enter yur pin : ")
        val pin = readLine()!!  // !! converts Nullable to non-nullable
        attempts++  // number of attempts
    }while(pin != actualPIN && attempts<3)
}		

Where the loop will iterate a maximum of three times to allow entry of a valid PIN number. A while loop could also be used here.

So what is the difference? It simply depends upon whether the algorithm requires that the body of the loop needs to run once first before deciding whether the loop will continue.

If so, use a do…while loop, otherwise you should use a while loop.


fun main(args:Array<String>)
{
    var i = 0
    do{
        println(i)
    }while(i>10) // result false
}	

Classes in kotlin

For Loop and types in Kotlin

For loop is used to execute the same set of statements again and again, There is not traditional for loop is in Kotlin that means No initialization or condition increment/decrement.

To replace the traditional for loop kotlin uses ranges, in operator, iterators(for collections).

The in operator is always used in for loop whether you use ranges or collections.

    For Loop can be used in different places in Kotlin.
  • For Loop with Ranges
  • Until function in Kotlin
  • step in kotlin
  • For loop with collections
  • For loop Iterating over array

For Loop with Ranges :

What is range in kotlin ?
A range is consecutive values between given lower and upper limit, and the value could be either number character or objects. Range either could be in incremental or decremental and the difference between two value always would be 1 (you can also say step is 1)

In Kotlin incremental range is generated with the .. (double dots) operator or with the rangeTo() function and the decremental range is created with downTo() function.

Incremental Range : 1 .. 10 => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
Decremental Range : 10.downTo(1) => 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 Example for incremental range.


fun main(args:Array<String>)
{
    // incremental for loop with ..
    for(value in 1..3){
        println(value)
    }
    println("**************************************")
    // incremental for loop with rangeTo
    for(valFun in 6.rangeTo(9)){
        println(valFun)
    }
}	

Example for Decremental range.


fun main(args:Array<String>)
{
    // decremental for loop with downTo
    for(valFun in 6.downTo(2)){
        println(valFun)
    }
}	

Yeah, i got your intention lets try it to decremental with .. or incremental with downTo


fun main(args:Array<String>)
{
    // decremental for loop with .., nothing happens
    for(value in 6..2){
        println(value)
    }
	
	// incremetal with downTo
	println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
    for(valFun in 3 downTo 9){
        println(valFun)
    }
	
}	

As you have witnessed nothing happened and control never went inside for loops. We can also use the downTo functions as operator.


fun main(args:Array<String>)
{
    for(valFun in 9 downTo 3){
        println(valFun)
    }
}	

Until function in Kotlin :

In Kotlin, until function returns a range from given lower value to higher value but excluding the higher value.

For Example if use 1 until 5, in this the values are 1, 2, 3, 4 only.


fun main(args:Array<String>)
{
    for(valFun in 3 until 9){
        println(valFun)
    }
}	

step in kotlin (Progression) :

Step is interval between number or you can also say the step is the difference between two consecutive values in the ranges we generate using above methods.


fun main(args:Array<String>)
{
    for(valFun in 3..9 step 2){
        println(valFun)
    }
}	

For loop with collections :

We can use the for loop along with collection in kotlin using the in operator, in this case all the elements present in the collection will be covered, and the all elements are over for loop will be terminated.

We will receive the current element into loop variable, in below example element is the loop variable Going through list


fun main(args:Array<String>)
{
    var list = listOf(1, "abc", true, 10.99)
    for(element in list){
        println(element)
    }
}	

Going through set


fun main(args:Array<String>)
{
    var set = setOf(1, "abc", true, 10.99)
    for(element in set){
        println(element)
    }
}	

List maintain elements in order but set doesn't, we will learn about list and set in collections chapter.

For loop Iterating over array :

We can iterator over a array using the index of the array elements for this purpose we have to know the size/length of the array.


fun main(args:Array<String>)
{
    var arr = arrayOf(1, 4, 17, 34)
    var len = arr.size
    for(element in 0 until len){
        println(arr[element])
    }
}	

We can also iterator over an array as like collections


fun main(args:Array<String>)
{
    var arr = arrayOf(1, 4, 17, 34)
    for(element in arr){
        println(element)
    }
}	

Break and Continue

Break statement is used to break a loop, it breaks the nearest loop. Once the loop is broken then the loop is over.

You can use break with all the loop not just with for loop.


fun main(args:Array<String>)
{
    for(element in 0 until 10){
        println(element)
        if(element ==6 ){
            break
        }
    }
}	

Break nested loop in kotlin :

Sometimes we might want to break a specific loop rather than nearest loop, in such cases we can provide names for the loop and terminate them by calling their name.

If you want to provide a name for a loop then you must prefix name@ here name follow the rules of variable name and the @ is mandatory to denote that it is the name.

While breaking the loop you should use the break@name, here 'name' is nothing but loop name that we have provided.


fun main(args:Array<String>)
{
    a@for(element in 0 until 10){
        b@for(element1 in 0 until 10){
            println("$element => $element1")
            if(element == 5 && element1 ==5){
                break@a
            }
        }
    }
}	

Continue in kotlin loops :

Continues make the loop to ignore the body or statement after the continues for that iteration and start over with next (incremental/decremental or with next element)

Continue can be applied to nearest loop f we don't provide the loop name otherwise it affect the loop with given name

Below kotlin code don't print the series with 2->0, 2->1, 2->2, 2->3 as we are using continue.


fun main(args:Array<String>)
{
    a@for(element in 0 until 4){
        b@for(element1 in 0 until 4){
            if(element == 2 && element1 == 0){
                continue@a
            }
            println("$element => $element1")
        }
    }
}	

Lazy initialization

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group