repeat

while and for are just repeating blocks

Repeat

KotlinPoetDSL offers supports for three very basic repeats. There is not a lot to talk about, to be honest. But on the positive side, boring code and implementations are often the best.

for

for (i in 0 until 5) {
    println(i)
}

can be written as:

createCodeBlock {
    forEach("i in 0 until 5"){
        statement("println(i)")
    }
    
    // or like
    forEach("i in %L until %L", 0, 5){
        statement("println(i)")
    }
    // yep this is possible in a lot of places.
    // but I need to have something to talk about...
}

before V0.2, the repeat inside code-block which accepts a number doesn't map to KotlinPoetDSLs repeat but to kotlins repeat. (KotlinPoetDSL made a mistake by temporarily removing it).

while

while is reserved, so I called it repeatWhile.

repeatWhile("true"){
    statement("prints forever!")
}

maps to

while (true) {
    //prints forever!
}

if you want one more than forever, use do-while.

do {
    //prints forever + 1 :-)
} while (true)

This can be written in two ways:

doRepeat {
    statement("//prints forever + 1 :-)")
}.forEver()

doRepeat {
    statement("//prints forever + 1 :-)")
} asLongAs "true"

Last updated