Kotlin 'when' statement vs Java 'switch'

前端 未结 10 1119
感情败类
感情败类 2020-12-03 06:41

Pattern matching in Kotlin is nice and the fact it does not execute the next pattern match is good in 90% of use cases.

In Android, when database is updated, we use J

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 06:59

    What about Kotlin DSL for custom implementation? Something like this approach:

    class SwitchTest {
    
        @Test
        fun switchTest() {
    
            switch {
                case(true) {
                    println("case 1")
                }
                case(true) {
                    println("case 2")
                }
                case(false) {
                    println("case 3")
                }
                caseBreak(true) {
                    println("case 4")
                }
                case(true) {
                    println("case 5")
                }
    //          default { //TODO implement
    //
    //          }
            }
        }
    }
    
    class Switch {
        private var wasBroken: Boolean = false
    
        fun case(condition: Boolean = false, block: () -> Unit) {
            if (wasBroken) return
            if (condition)
                block()
        }
    
        fun caseBreak(condition: Boolean = false, block: () -> Unit) {
            if (condition) {
                block()
                wasBroken = true
            }
        }
    }
    
    fun switch(block: Switch.() -> Unit): Switch {
        val switch = Switch()
        switch.block()
        return switch
    }
    

    It prints: case 1 case 2 case 4 UPD: Some refactorings and output example.

提交回复
热议问题