Kotlin 'when' statement vs Java 'switch'

前端 未结 10 1041
感情败类
感情败类 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 07:00
    val orders = arrayListOf(
                { upgradeFromV1()},
                { upgradeFromV2()},
                { upgradeFromV3()}
    )
    
    orders.drop(oldVersion).forEach { it() }
    
    0 讨论(0)
  • 2020-12-03 07:09

    edit: Original response below. Here's what I'm currently doing:

    fun upgrade() {
        fun upgradeFromV1() { /* Do stuff */ }
        fun upgradeFromV3() { /* Do stuff */ }
    
        tailrec fun upgradeFrom(version: Int): Unit = when (version) {
            LATEST_VERSION -> {
                Config.version = version
            } 1 -> {
                upgradeFromV1()
                upgradeFrom(2)
            } in 2..3 -> {
                upgradeFromV3()
                upgradeFrom(4)
            } else -> {
                Log("Uncaught upgrade from $version")
                upgradeFrom(version+1)
        }
    
        upgradeFrom(Config.version)
    }
    

    Here's a variation on the answer @C.A.B. gave:

    fun upgrade(oldVersion: Int) {
        when (oldVersion) {
            latestVersion -> return
            1 -> upgradeFromV1()
            2 -> upgradeFromV2()
            3 -> upgradeFromV3()
        }
        upgrade(oldVersion + 1)
    }
    
    0 讨论(0)
  • 2020-12-03 07:12

    Simple but wordy solution is:

    if (oldVersion <= 1) upgradeFromV1()
    if (oldVersion <= 2) upgradeFromV2()
    if (oldVersion <= 3) upgradeFromV3()
    

    Another possible solution with function references:

    fun upgradeFromV0() {}
    fun upgradeFromV1() {}
    fun upgradeFromV2() {}
    fun upgradeFromV3() {}
    
    val upgrades = arrayOf(::upgradeFromV0, ::upgradeFromV1, ::upgradeFromV2, ::upgradeFromV3)
    
    fun upgradeFrom(oldVersion: Int) {
        for (i in oldVersion..upgrades.lastIndex) {
            upgrades[i]()
        }
    }
    
    0 讨论(0)
  • 2020-12-03 07:12

    Another variation of OP's answer:

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        when (oldVersion) {
            newVersion -> return
            1 -> TODO("upgrade from v1 to v2")
            2 -> TODO("upgrade from v2 to v3")
        }
        oldVersion++
        onUpgrade(db, oldVersion, newVersion)
    }
    
    0 讨论(0)
提交回复
热议问题