Kotlin 什么时候是穷尽的,那么其他的是多余的?

Kotlin 什么时候是穷尽的,那么其他的是多余的?,kotlin,appium,Kotlin,Appium,我是kotlin的新手,我创建了一个方法,其中包含when语句和IntelliJ,建议我删除else分支。 我真的不知道为什么。知道我为什么需要删除这里的else分支吗? 代码如下: companion object{ @Synchronized fun getDriver( url: String, desiredCapabilities: DesiredCapabilities, mobilePlatform: MobilePl

我是kotlin的新手,我创建了一个方法,其中包含when语句和IntelliJ,建议我删除else分支。 我真的不知道为什么。知道我为什么需要删除这里的else分支吗? 代码如下:

    companion object{
    @Synchronized fun getDriver(
        url: String,
        desiredCapabilities: DesiredCapabilities,
        mobilePlatform: MobilePlatform)
        : AppiumDriver<WebElement> =
        when(mobilePlatform){
            MobilePlatform.ANDROID -> AndroidDriver<WebElement>(URL(url), desiredCapabilities)
            MobilePlatform.IOS -> IOSDriver<WebElement>(URL(url), desiredCapabilities)
            else -> throw RuntimeException("Cannot get the driver")
        }
}

当您用尽了所有可能的选项,没有理由拥有else分支时。这样做的另一个好处是,在向枚举添加元素后,如果不扩展when,就会出现编译器错误

在kotlin中,当在密封类对象上时,如果覆盖了所有可能的内部情况,则不需要else

样品密封等级:

假设上面是一个密封的类,那么类a的任何对象,比如说a,都可以在a中使用,而不必在返回时使用

return when(a) {
  is A.B -> return something
  is A.C -> return something
} // no need of else here as all cases are covered.
这里有一个陷阱,如果你只需要检查一个条件,假设是A。B你可以写一个其他的。另外,请注意,如果只是一个语句,您不需要编写详尽的条件/否则

示例如下:

希望这有帮助

要使用else块,您可以尝试以下方法:

    enum class PaymentStatus(val value: Int) {
     PAID(1),
     UNPAID(2) 
 }

    fun f(x: Int) {
    val foo = when (x) {
        PaymentStatus.PAID.value -> "PAID"
        PaymentStatus.UNPAID.value -> "UNPAID"

        else -> throw IllegalStateException()
    }
}

创建工厂方法在enum类的伴随对象中创建:

检查更多详细信息

如果MobilePlatform是一个枚举,并且除了ANDROID和IOS之外没有任何值,则不需要其他分支。
some code ...
when(a) {
      is A.B -> do some task
}
more code ...
    enum class PaymentStatus(val value: Int) {
     PAID(1),
     UNPAID(2) 
 }

    fun f(x: Int) {
    val foo = when (x) {
        PaymentStatus.PAID.value -> "PAID"
        PaymentStatus.UNPAID.value -> "UNPAID"

        else -> throw IllegalStateException()
    }
}
enum class PaymentStatus(val value: Int) {
    PAID(1),
    UNPAID(2);

    companion object {
        fun create(x: Int): PaymentStatus {
            return when (x) {
                1 -> PAID
                2 -> UNPAID
                else -> throw IllegalStateException()
            }
        }
    }
}

fun f(x: Int) {
    val foo = when (PaymentStatus.create(x)) {
        PaymentStatus.PAID -> "PAID"
        PaymentStatus.UNPAID -> "UNPAID"
    }
}