Both ```when (it) { is EventDriver.Stop ->...
# getting-started
c
Both
Copy code
when (it) {
    is EventDriver.Stop -> ...
    is EventDriver.Go -> ...
}
and
Copy code
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
The first is doing a type check, the second is doing equality.
c
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
if it’s a sealed class with only object leafs, equality is fine. If you had something like:
Copy code
sealed class EventDriver {
  sealed class Go: EventDriver() {
    object Forward: Go()
    object Backward: Go()
  }
  object Stop: EventDriver()
}
Then you would either want to do:
Copy code
when(it) {
  EventDriver.Stop -> ...
  EventDriver.Go.Forward -> ...
  EventDriver.Go.Backward -> ...
}
or
Copy code
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
Thanks @phldavies I think I will opt to ALWAYS omit the
is
when working with sealed classes and
when
statement
n
the sealed class part isn't the key part here -- it's that the "classes" you're testing are in fact objects.
☝️ 1
c
Oh. So its that I have objects... this is making more sense.
b
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.
Copy code
when (it) {
   is EventDriver.Go -> accelerate(it.mph)
   is EventDriver.Stop -> stop(it.car)
}