https://kotlinlang.org logo
Title
c

Colton Idle

08/14/2020, 6:58 AM
Both
when (it) {
    is EventDriver.Stop -> ...
    is EventDriver.Go -> ...
}
and
when (it) {
    EventDriver.Stop -> ...
    EventDriver.Go -> ...
}
seem to compile and run fine. What's the difference? I would have expected
is
to be required here?
p

phldavies

08/14/2020, 7:31 AM
The first is doing a type check, the second is doing equality.
c

Colton Idle

08/14/2020, 8:01 AM
Hm. I'm not sure which one I want? I'm just sending an eventDriver type which is a sealed class. Is there a typical route to use here?
p

phldavies

08/14/2020, 8:29 AM
if it’s a sealed class with only object leafs, equality is fine. If you had something like:
sealed class EventDriver {
  sealed class Go: EventDriver() {
    object Forward: Go()
    object Backward: Go()
  }
  object Stop: EventDriver()
}
Then you would either want to do:
when(it) {
  EventDriver.Stop -> ...
  EventDriver.Go.Forward -> ...
  EventDriver.Go.Backward -> ...
}
or
when(it) {
  is EventDriver.Go -> ...
  EventDriver.Stop -> ...
}
You can still do type checking with Stop for consistency if you wanted, as only that single object will satisfy the type check, but the
is
in that case would be superfluous
c

Colton Idle

08/14/2020, 1:51 PM
Thanks @phldavies I think I will opt to ALWAYS omit the
is
when working with sealed classes and
when
statement
n

nanodeath

08/14/2020, 2:07 PM
the sealed class part isn't the key part here -- it's that the "classes" you're testing are in fact objects.
☝️ 1
c

Colton Idle

08/14/2020, 3:07 PM
Oh. So its that I have objects... this is making more sense.
b

brandonmcansh

08/14/2020, 9:21 PM
If you have data classes in your sealed class will auto type cast it when using
is
and give you direct access to its members.
when (it) {
   is EventDriver.Go -> accelerate(it.mph)
   is EventDriver.Stop -> stop(it.car)
}