Do equality checks in `when` statements not trigge...
# random
s
Do equality checks in
when
statements not trigger a smart cast? ie:
Copy code
sealed interface Foo
object Bar: Foo
object Baz: Foo

when (foo) {
    Bar -> // typechecked as Foo, cannot use as Bar without a casting
    is Baz -> // smart-cast as Baz
}
I thought using the equality syntax would allow smart-casting, but I get a type error in my project if I do this. I tried on Kotlin 2.2.20 (link) and also on an older Kotlin version too (link)
For some reason I swear something like this has worked for me in the past, but clearly not 😅
e
equals
is overridable, so
foo.equals(Bar)
does not necessarily mean that
foo is Bar
👍 2
of course in this case you can see that there are no overrides of
equals
, but in general it is possible
s
Ah there's no satisfying "aha" emoji
💡 1
I didn't consider the case of override
equals
, thanks @ephemient!
y
I wish it'd work with
data object
at least, but I guess you still could override
equals
there
s
Yeah this feels like something that should just work, but the nice thing is the fix is easy (just use an
is
check) and it's good that Kotlin is keeping a foot gun away from us by ensuring an overridden equals doesn't blow up the program