Home / Programming / Kotlin / Kotlin: Break and Continue Statements

Kotlin: Break and Continue Statements

Break and Continue Statements allow us to define jumps in our code and they are used inside Loops

breakstatement allow us to jump to the end of the loop and halt any further iterations. This is useful whenever we  are interested in the first occurrence of something.

val string = "Kotlin"
    for (char in string){
    if (char == 'i'){
       break //this will totally halt the loop whenever char 'l' is found
    }
    print(char)
} //output = Kotl

continuestatement allows us to skip the current iteration and move to the next one. It skips only one iteration and starts with the next iteration inside the loop. An example is when you want to work with users who only have the character ‘o’ within the spelling of their name.

val friends = arrayOf("Brymo","Jemaima","Brian", "Cooper", "Michelle", "Hugo", "Khan", "Opeyemi", "Timothy", "Victor")
    for (element in friends){
   if (element.contains('o', true)){ // contain char 'o', ignoreCharCase = true
       println(element)
   } else {
       continue // this line skips the iteration when element does not contain char 'o'
   }   
}
/*
Brymo
Cooper
Hugo
Opeyemi
Timothy
Victor
*/
You should use these jump statements (break and continue) sparingly because they can make your code quite confusing because jumps can be quite hard to follow, so you may run into bugs because of these jumps although there are legitimate use cases. Do use them if you really need them, but avoid them when it’s not necessary

 

About Edge Developer

Hey there! am Opeyemi Olorunleke (aka Edge Developer), an Android developer. I Love Sharing Android Tutorials and code snippets.

Check Also

recycler view multi select tutorial

RecyclerView Multi-Select using KOTLIN

Implementing multi-select on a Recycler View can be tricky and complicated. However, by the end …

Leave a Reply

Your email address will not be published. Required fields are marked *