Nir
01/15/2021, 4:01 PMclass BreakException : Exception("")
class Breaker {
fun breakOut() { throw BreakException(); }
}
class ForEachElser(val runElse: Boolean)
fun <T> Iterable<T>.forEachElse(func: Breaker.(t: T) -> Unit): ForEachElser {
val b = Breaker()
return try {
forEach{ b.func(it) }
ForEachElser(true)
}
catch (b: BreakException) {
ForEachElser(false)
}
}
infix fun ForEachElser.elser(func: () -> Unit) { if(runElse) func() }
(1..5).forEachElse {
if (it == 6) {
println("x is 5")
breakOut();
}
} elser {
println("hello")
}
Casey Brooks
01/15/2021, 4:11 PMNir
01/15/2021, 4:26 PMholgerbrandl
01/15/2021, 4:28 PMNir
01/15/2021, 4:30 PMholgerbrandl
01/15/2021, 4:31 PMNir
01/15/2021, 4:31 PMMatteo Mirk
01/15/2021, 4:43 PMnp. It’s just a pity we’re not allowed to somehow use names like break and else here,actually you can but you need to enclose them in backticks: `infix fun ForEachElser.`else`(...)` they’re needed for invocation as well
Nir
01/15/2021, 4:50 PMMatteo Mirk
01/15/2021, 4:50 PMNir
01/15/2021, 4:51 PMMatteo Mirk
01/15/2021, 4:55 PMfun `should add two numbers`() { ...
Kotlin DSLs are one of the reasons I started loving this language, but apart from this naming nuisance they let you write very neat code!holgerbrandl
01/15/2021, 4:56 PMYoussef Shoaib [MOD]
01/15/2021, 7:28 PMEffect
interface for your own type and have it so that whenever breakOut is called you'll control().reset(//some value)
out of it. Maybe check out the #arrow channel for more detailed information and demosNir
01/15/2021, 7:35 PM