When using the `when` expression to test some case...
# announcements
v
When using the
when
expression to test some cases, why do I have to use the
is
keyword sometimes, and other times I don’t?
m
is
compares Types. It's an operator of sorts.
v
But sometimes its the IDE forces me to add the
is
keyword and other times it doesn’t, why is that the case?
d
I'm guessing
is
won't be required is it's an
object
?
v
that’s correct, but is there a reason for this?
v
is
is basically an
instanceOf
check. Enums and objects are singletons so there is no need to perform an
instanceOf
comparison
v
great, thank you
d
The questions has been answered but I don't want to discard mine, so I'll leave it here. 😅 Say we have.
Copy code
sealed class Example
data class Wrap(val value: Int): Example()
object None : Example()

val tmp: Example = TODO(...)
I think it's because you can do
if (tmp == None)
or
if (tmp is None)
but you can only do
if (tmp is Wrap)
. I'm sure you know why
if (tmp == Wrap)
doesn't work.
a
I use
is
when checking for `object`s anyway. This way
when
looks less cluttered and if later I decide to convert the object to a
data class
I don’t have to change the code in every
when
it occurred
And I’m not the only one to prefer it this way https://kotlinlang.slack.com/archives/C4GKV43N2/p1562270360031400