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")
}
}
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
.
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 !!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With