Kotlin“何时"声明与Java"switch" [英] Kotlin 'when' statement vs Java 'switch'

查看:69
本文介绍了Kotlin“何时"声明与Java"switch"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中,模式匹配非常好,并且在90%的用例中,不执行下一个模式匹配这一事实也很不错.

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

在Android中,当数据库更新时,如果不让代码看起来像这样,我们将使用Java开关属性进行下一种情况:

In Android, when database is updated, we use Java switch property to go on next case if we do not put a break to have code looking like that:

switch (oldVersion) {
    case 1: upgradeFromV1();
    case 2: upgradeFromV2(); 
    case 3: upgradeFromV3();
}

因此,如果某人拥有一个数据库版本为1的应用程序,而错过了DB v2的应用程序版本,那么他将获得所有所需的升级代码.

So if someone has an app with version 1 of the DB and missed the app version with DB v2, he will get all the needed upgrade code executed.

转换为Kotlin后,我们陷入了混乱:

Converted to Kotlin, we get a mess like:

when (oldVersion) {
    1 -> {
        upgradeFromV1()
        upgradeFromV2()
        upgradeFromV3()
    }
    2 -> {
        upgradeFromV2()
        upgradeFromV3()
    }
    3 -> {
        upgradeFromV3()
    }
}

这里只有3个版本,想象一下DB达到19版时.

Here we have only 3 versions, imagine when DB reaches version 19.

以相同的方式做出任何决定然后切换?我试图继续走下去,没有运气.

Anyway to makes when acting in the same way then switch? I tried to continue without luck.

推荐答案

简单但冗长的解决方案是:

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]()
    }
}

这篇关于Kotlin“何时"声明与Java"switch"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆