Home > Net >  How to break forEach loop inside "let" lambda?
How to break forEach loop inside "let" lambda?

Time:12-21

To optimize my loop i need to break it if my "if" construction is true. For example:

radioGroup.forEach { button ->
     button.color?.let {
         if (it = myColor) {
            println("Color fits!")
            /** Here i need to break radioGroup.forEach loop because i found color */
         }
     }
}

But i can call "break" only inside a loop. Can you help me with it?

CodePudding user response:

An alternative to the other answers here is to use:

radioGroup.firstOrNull { button -> button.color == myColor }?.let {
    println("Color fits!")
    //"it" is the matched button here
}

What's nice is that inside the let you will have access to the matched button as the it variable.

CodePudding user response:

You need to use run block with label name and stop it with your condition, for example

run loop@ {
    radioGroup.forEach { button ->
        button.color?.let {
            if (it = myColor) {
                println("Color fits!")
                return@loop
            }
        }
    }
}

CodePudding user response:

There are 3 ways to achieve that:

  1. You can use return with a label:
run loop@{
    radioGroup.forEach { button ->
        println(button)
        button.color?.let {
            if (it == myColor) {
                println("Color fits!")
                return@loop
            }
        }
    }
}
  1. You can create a function and use return keyword something like that:
fun fits(radioGroup: List<Button>, myColor: String): Boolean {
    radioGroup.forEach { button ->
        button.color?.let {
            if (it == myColor) {
                return true
            }
        }
    }
    return false
}
  1. Or just get rid of returns at all:
if (radioGroup.any { button -> button.color == myColor }) {
    println("Color fits!")
}
  • Related