Sunday 15 September 2019

Kotlin Code to break forEach inline loops

In General we are unable to break the forEach inline loops.  Please check the below tries and see the proper way to do so.

1
2
3
4
5
6
7
8
9
 var data = listOf<String>("Dev", "Prd", "Test", "Sbx", "demo")
    data.forEach {
        if (it.equals("Prd")) {
            println("I'm Selected $it")
            return
        }
        println("I'm in the list $it")
    }
    println("Done")

the above code produces the below output, if we use "return" on the line 5 we will be getting the below output, because that will abundantly break and come out of the method.  You can see the "Done" is not printed.

I'm in the list Dev
I'm Selected Prd

Hence to resolve we can try out with the label concept available in kotlin,  Since our programming language says there is no explicit label needed for the inline function. we can directly use it as "return@forEach".  But this will also lead to be failed, this produces the below output.

I'm in the list Dev
I'm Selected Prd
I'm in the list Test
I'm in the list Sbx
I'm in the list demo
Done

The highlighted text are unnecessary to this case.  In the below code snippet run block with label is used to break the loop as soon as we get the expected result and breaks the blocks and proceeds the normal flow function flow.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var data = listOf<String>("Dev", "Prd", "Test", "Sbx", "demo")
    run envBlock@{
        data.forEach {
            if (it.equals("Prd")) {
                println("I'm Selected $it")
                return@envBlock
            }
            println("I'm in the list $it")
        }
    }
    println("Done")

And will get the expected output.


I'm in the list Dev
I'm Selected Prd
Done

Happy Coding :-)

No comments: