If

Flow

If exists out of multiple parts that can indefinately be chained: if, else if and else. Because KotlinPoetDSL adds completed components to code and not uncompleted code, KotlinPoetDSL needs to know if an if-statement needs to be finished.

This can be done with an additional wrapper around the if-statement, or requiring to call an closing function: endIf or else. KotlinPoetDSL choose for the second option.

When the if is not finished, there are two things we can do: either don't add it, or throw an exception. Because the code is generated inside the DSL, just ignoring the if can lead to confusion. Therefor, KotlinPoetDSL throws exceptions.

ifp, ifn, If

KotlinPoetDSL has three kinds of if:

Code

Okidoki, here we go!

ifp("null"){
    statement("println(%S)", "null == true!!!")
}.orElseIfn("null") {
    statement("println(%S)", "null == true!!!")
} orElse {
    statement("println(%S)". "Kotlin works correctly.")
}

will evaluate to:

if ((null) == true) {
    println("null == true!!!")
} else if ((null) == false) {
    println("null == true!!!")
} else {
    println("Kotlin works correctly.")
}

Last updated