Kotlin 'when' 语句与 Java 'switch' [英] Kotlin 'when' statement vs 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();
}
因此,如果某人有一个使用 DB 版本 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 'when' 语句与 Java 'switch'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!