Kotlin 'when' statement vs Java 'switch'

前端 未结 10 1118
感情败类
感情败类 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:49

    Here is a mix of the two answers from bashor, with a little bit of functional sugar:

    fun upgradeFromV0() {}
    fun upgradeFromV1() {}
    fun upgradeFromV2() {}
    fun upgradeFromV3() {}
    
    val upgrades = arrayOf(::upgradeFromV0, ::upgradeFromV1, ::upgradeFromV2, ::upgradeFromV3)
    
    fun upgradeFrom(oldVersion: Int) {
        upgrades.filterIndexed { index, kFunction0 -> oldVersion <= index }
                .forEach { it() }
    }
    

提交回复
热议问题