4

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)
HelloCW
  • 843
  • 22
  • 125
  • 310

2 Answers2

11

Use the traditional way "for-each" loop.

i.e. change

people.forEach label@{

to

for (it in people) {

and change return to break.


NOTE: Read these articles about `return` in `.forEach()`

`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)

Naetmul
  • 14,544
  • 8
  • 57
  • 81
1

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" }
}
advice
  • 5,778
  • 10
  • 33
  • 60