How can I use a keyword "break" in foreach ? In J...
# getting-started
o
How can I use a keyword "break" in foreach ? In Java I have this
Copy code
for (it in this.list) {
                if (it == example) {
                    //do smth
                    break
                }
            }
In Kotlin I use:
Copy code
this.list.foreach{
    if(it==example) //do smth
}
I can't use "break" in foreach. I get an error: "Break & continue is only allowed inside a loop".
m
Try
return@foreach
o
It is just skip in preset case http://prntscr.com/mk22v2
I have found the solution 🙂 I can use a keyword "first". Now my code is: this.list.first { it == example }.apply { this.amount = +1 }
💯 2
m
Ah, right. To simulate a break, you have to label an outer scope. You can use
run
to make that scope.
Copy code
run {
  listOf(1,2,3,4,5).forEach {
    if (it == 3) return@run
    print(it)     
  }
}
👍 1
o
ok, thanks, I 'll keep in mind your solution too)
I saw that page but I have not found any solution for my case
m
It's the last example with the
run loop@
label.
o
You are right, I just have not noticed it.
u
A different solution is to use tail recursion instead
j
I believe you could do something like:
Copy code
this.list.filter{ it == example }.apply { ... }
to do the same thing.
o
@Jake I think this filter will be going through the whole list and will not stop when some match is found
But I need just get an item from the "Set"
m
So you want to find the first item that matches some criteria? In that case, you should use
find
.
👍 1
✔️ 1
a
Also this isn't for your case but in general, another common case for breaking out of loop is to stop iterating once a certain condition is met. For that there's takeWhile method
s
Am I missing something? Is there something that makes a regular
for (item in list)
foreach loop not acceptable now?
Like, sure,
first()
or
find()
is more appropriate for this particular use case but nothing wrong with using regular ol’ loops in Kotlin when you need to
a
It may already be part of a bigger chain
o
it is acceptable, but I was looking more short form of code)
s
using
forEach
at the end of a functional chain is fine, but is still really only geared towards cases where you’re okay with applying your transform to every element of whatever iterable you’re working on
s
Actually your first code snippet
for (it in this.list)
it is Kotlin too... In both Java and Kotlin you still have
forEach
too...