问题描述
Kotlin中的模式匹配很好,并且它在90%的用例中都没有执行下一个模式匹配。
Pattern matching in Kotlin is nice and the fact it does not execute 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 version, imagine when DB reaches version 19 :/
无论如何以与开关相同的方式进行操作?我试着继续没有运气。
Anyway to makes when acting in the same way than switch? I tried 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]()
}
}
这篇关于"当"声明与Java“切换”声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!