Kotlin: Break and Continue Statements

Liked this Post?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on reddit
Share on Reddit
Share on linkedin
Share on LinkedIn
Share on whatsapp
Share on WhatsApp
Share on telegram
Share on Telegram

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]


About the Author

Edge Developer

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 Posts

Leave a Comment

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