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
} //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
   } else {
       continue // this line skips the iteration when element does not contain char 'o'

[box type=”info” align=”alignleft” class=”” width=””]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[/box]



Edge Developer

Hello there, my name is Opeyemi Olorunleke. I am a Software Developer (majorly Android, GitHub Profile), Digital Marketer, Udemy Instructor, Technical Writer, Blogger & Webmaster.

Related Articles

Leave a Reply

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

Check Also

Back to top button