KotlinPoetDSL
  • Welcome
  • Prerelease
  • Building
  • Structure
  • differences to KotlinPoet
    • Variable
    • ConstructorSpec
    • Inline properties
  • codeBlock
    • Intro to CodeBlock
    • CodeBlock-Structure
    • Switch
    • If
    • repeat
Powered by GitBook
On this page

Was this helpful?

  1. codeBlock

Switch

When in KotlinPoetDSL is switch

Just let me see the code

Switch is very straight forward. Therfore I will show the code in Kotlin and then the the code in KotlinPoetDSL.

when(1){
    1 -> println(1)
    2 -> when("a"){
        "a" -> println(1)
        else -> throw NullPointerException()
    } 
    3 -> {
        println(1)
        println(2)
    }
    else -> TODO()
}

Will be generated by:

createCodeBlock {
    switch("1"){
        "1" then "println(1)"
        "2" then switch("a".S()){
            "a".S() then "println(1)"
            Else{
                statement("throw %T()", typeNameFor<NullPointerException>())
            }
        }
        "3" then {
            statement("println(1)")
            statement("println(2)")
        }
        Else("TODO()")
    }
}

it actually generates the following, but it's the same:

when(1) {
    1 -> {
        println(1)
    }
    2 -> {
        when("a") {
            "a" -> {
                println(1)
            }
            else -> {
                throw java.lang.NullPointerException()
            }
        }
    }
    3 -> {
        println(1)
        println(2)
    }
    else -> {
        TODO()
    }
}

PreviousCodeBlock-StructureNextIf

Last updated 6 years ago

Was this helpful?