Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return outside of forEach in Kotlin? [duplicate]

Tags:

android

kotlin

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)
like image 600
HelloCW Avatar asked Aug 30 '25 17:08

HelloCW


2 Answers

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)

like image 199
Naetmul Avatar answered Sep 02 '25 05:09

Naetmul


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" }
}
like image 43
Advice-Dog Avatar answered Sep 02 '25 05:09

Advice-Dog