Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when is exhaustive so else is redundant?

Tags:

kotlin

appium

I am new to kotlin and I created a method that contains the when statement and IntelliJ suggesting me to remove the else branch. I am not really sure why. Any idea why I need to remove the else branch here? This is the code:

    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")
        }
}
like image 884
kidulf Avatar asked Feb 17 '20 10:02

kidulf


2 Answers

When you have exhausted all possible options of when there is no reason to have an else branch. This has the added advantage that you get a compiler error after adding elements to the enum without extending the when.

like image 95
Christoph Grimmer-Dietrich Avatar answered Oct 21 '22 21:10

Christoph Grimmer-Dietrich


In kotlin, when on a sealed class object doesn't require else if all possible inner cases are covered.

Sample sealed class:

sealed class A {
 object B: A()
 object C: A()
}

Let the above be a sealed class then any object of class A (lets say a), can be used inside a when exhaustively(not necessarily) while returning

return when(a) {
  is A.B -> return something
  is A.C -> return something
} // no need of else here as all cases are covered.

There is one catch here, if you just need to check for one condition, let's say is A.B you can write an else. Also, please note that, you need NOT write exhaustive conditions/else if it's just a statement.

Example below:

some code ...
when(a) {
      is A.B -> do some task
}
more code ...

Hope this helps !!

like image 34
vizsatiz Avatar answered Oct 21 '22 20:10

vizsatiz