Skip to content

Kotlin basics : Looping mechanisms

Devrath edited this page Dec 24, 2023 · 3 revisions

While Loop

  • We use this construct to execute iterate a collection of elements until a condition is met
  • We use the while looop when we are not sure how many loops are needed until a condition is met
  • Thus we set a condition
 private fun initiate() {
        // List of cities
        var cityList = listOf("Bangalore","Delhi","Chennai","Calcutta")
        executeWhileLoop(cityList)
    }

    private fun executeWhileLoop(cityList: List<String>) {
        var i=0
        while (i<cityList.size-1){
            println(cityList[i])
            i++
        }
}

doWhile Loop

  • We use the doWhile loop when we are not sure how many loops are needed until a condition is met.
  • Thus we set a condition
  • This is the same as the do-while loop but here we execute the statements and then check the condition, which is in reverse order for doWhile loop.
 private fun initiate() {
        // List of cities
        var cityList = listOf("Bangalore","Delhi","Chennai","Calcutta")
        executeDoWhileLoop(cityList)
    }

    private fun executeDoWhileLoop(cityList: List<String>) {
        var i=0
        do {
            println(cityList[i])
            i++
        }while (i<cityList.size-1)
    }
}

For Loop

  • We use the for a loop when we know the number of iterations we need to perform.
  • We use the range for this purpose.
private fun initiate() {
        // List of cities
        var cityList = listOf("Bangalore","Delhi","Chennai","Calcutta")
        executeForLoop(cityList)
    }

    private fun executeForLoop(cityList: List<String>) {
      for (city: String in cityList){
          println(city)
      }
    }
}

Using break and continue in looping

  • continue is a keyword used to skip execution of current iteration from the line it is mentioned in the loop.
  • break is a keyword used to skio execution of all left over iteration from the line it is mentioned int he loop.

Using custom label for the loop

  • We can assign a custom name as a tag for a loop and can refer to this label and use it to break the loop.
  • This is very useful in multidimensional or nested looping mechanism.
private fun initiate() {
        // List of cities
        var cityList = listOf("Bangalore","Delhi","Chennai","Calcutta")
        usingLabel(cityList)
    }

    private fun usingLabel(cityList: List<String>) {
        myLabel@for (city: String in cityList){
            if (city == "Calcutta"){
               break@myLabel
            }else{
                println(city)
            }
        }
}

Usage of when construct

  • we use this when we need to evaluate multiple expressions
// STRUCTURE
when(value) {
 expression1 -> statement1
 expression2 -> statement2
 expression3 -> statement3
 else -> statement4
}
Clone this wiki locally