I hope to return to the line aa@ logError("Done") outside forEach, but return@aa doesn't work, and break@label doesn't work too.
And more, if you use return, it will be return outside the fun lookForAlice !
data class Person(val name: String, val age: Int)
val people = listOf(Person("Paul", 30), Person("Alice", 29), Person("Bob", 31))
fun lookForAlice(people: List<Person>) {
people.forEach label@{
logError("Each: "+it.name)
if (it.name == "Alice") {
logError("Find")
return@aa //It's fault
}
}
aa@ logError("Done")
}
lookForAlice(people)
Use the traditional way "for-each" loop.
i.e. change
people.forEach label@{
to
for (it in people) {
and change return to break.
`break` and `continue` in `forEach` in Kotlin
How do I do a "break" or "continue" when in a functional loop within Kotlin? (The question may be a duplicate of this link)
You want to use find instead. It'll return Person?. So you can just check if it's null, or not. If not, you found Alice.
data class Person(val name: String, val age: Int)
val people = listOf(Person("Paul", 30), Person("Alice", 29), Person("Bob", 31))
val alice: Person? = findAlice(people)
fun findAlice(people: List<Person>): Person? {
return people.find { it.name == "Alice" }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With