break and continue is used together with a conditional statement like if.
1. break - It is used to put a stop on the loop. And would get out of that loop.
syntax 1:
while(true){
if(condition){
break
}
// other statement
}
2. continue - It is used to jump to the next condition of the loop.
syntax 1:
while(true){
if(condition){
continue
}
// other statement
}
3. break with a label and continue with a label - This works the same but with just a labelled loop. It uses an "@" after the label and they usually put before the loop.
==================
fun main(){
val list = listOf(
listOf("apple", "mango", "strawberry"),
listOf("car", "house"),
listOf("money", "foods", "travels", "bills")
)
looper/:/
for(x in list){
for(y in x){
if(y == "car"){
continue
}
if(y == "travels"){
break/:/looper
}
print("$y ")
}
println()
}
}
==================
Result:
apples mango strawberry
house
money foods
Note: I place /:/ in the label looper because there is a problem every time you place an "@" sign. Just replace the symbol with that at sign.
4. return with a label - this works the same way as the return statement but with a label.
=================
fun main(){
val yourList = listOf(
listOf("money", "car", "house"),
listOf("jump", "run", "walk")
)
yourList.stream()
.filter{ it != null}
.forEach looper/:/{
for(x in it){
if(x == "car"){
return/:/looper
}
print("$x ")
}
}
}
=================
Result:
money jump run walk
Note: Replace the /:/ with the at sign. You can also use the name of the function as the label.
return/:/forEach
YOU ARE READING
Kotlin Programming
RandomI have been trying to learn things online. I will put my notes in here. I put things in my own words and i do not copy their programs. I try to do things the right way so that i may learn. Below is the site where i study. Go check this out if you wa...
