The forEach status quo

Kotlin uses its own features to turn the for loop into a function, which is extremely convenient for some scenarios, but the forEarch function has a drawback.

Defects of the forEach function

ArrayListOf (1,2,3). ForEach {println(it)}Copy the code

This is forEach, but it has a flaw (compared to the for loop), so let’s look at the same for loop:

Val array = arrayListOf(1,2,3) for (value in array) {println(value)}Copy the code

Some people might think, well, isn’t that normal? It’s perfectly functional. What’s wrong with it?

ForEach is missing continue and Brack

This is what I see as the drawback of forEach so far

Implement continue and break

We all know that both continue and break can interrupt a for loop. When I think of breaks, I think of exceptions. As a result:

Object ForEach {val 'continue' : Unit get() = throw ContinueException // Create a continue custom exception val 'break' : Unit get() = throw BreakException object ContinueException : RuntimeException() object BreakException : RuntimeException() }Copy the code

The second step is to re-implement the forEach function:

inline fun <T> Iterable<T>.forEachPro(action: ForEach.(T) -> Unit): Unit { val foreach = ForEach for (element in this) { try { foreach.action(element) } catch (ex: ForEach. ContinueException) {continue / / a continue} the catch (ex: ForEach BreakException) {break / / execution break}}}Copy the code

The forEach function is global, so the name of the custom function is changed to forEachPro.

use

ArrayListOf (1,2). ForEachPro {if (it == 2) {' continue '} println(it)Copy the code