y
09/30/2024, 2:44 PMsealed interface Foo {
data class FooClass(val n: Int) : Foo {
fun hello() { /* ... */ }
}
data object FooObject : Foo {
fun hello() { /* ... */ }
}
}
fun main() {
val foo = getFoo()
when (foo) {
is Foo.FooClass -> foo.hello() // resolves
Foo.FooObject -> foo.hello() // does not resolve
}
}
why doesn't this resolve? am I supposed to call it as Foo.FooObject.hello()
?y
09/30/2024, 2:46 PMy
09/30/2024, 2:46 PMJoffrey
09/30/2024, 2:47 PMy
09/30/2024, 2:47 PMJoffrey
09/30/2024, 2:47 PMis
might not restrict the type itself. Have you tried with is
?y
09/30/2024, 2:48 PMJoffrey
09/30/2024, 2:48 PMfoo
variable anymore if you already know it's this specific object, so you can indeed simply use the object with Foo.FooObject.hello
Joffrey
09/30/2024, 2:49 PMhello
declaration up to the Foo
interface, so you don't even need a when
at ally
09/30/2024, 2:58 PMfoo
is Foo.FooObject
even without the is
. the compiler kinda left me in the dark here
as for hoisting the hello
to the interface, I wish I could do that but unfortunately the real version of `FooClass`'s hello
takes additional context as parametersJoffrey
09/30/2024, 2:59 PMy
09/30/2024, 3:00 PMJoffrey
09/30/2024, 3:01 PMAny
and you check for the value 42, we could get flow typing and restrict to Int
.Joffrey
09/30/2024, 3:02 PMfoo
is equal to a value doesn't mean that it's of the same type, actually!Joffrey
09/30/2024, 3:03 PMFooClass
overrides equals
and returns true
for FooObject
values? It would be incorrect to consider that the type is FooObject
Joffrey
09/30/2024, 3:04 PMis
- it's not the same check. It uses instanceof
, not equals
y
09/30/2024, 3:04 PMif (foo == Foo.FooObject) { /* still can't use foo as `FooObject` here */ }
also not working, suggests that this is likely intentionaly
09/30/2024, 3:07 PMinstanceof
imo the fact that IntellIJ "when branch autofill" assist fills objects as equality checks instead of is
checks, also adds to this confusion (it confused me)