Hey, is extending sealed classes bugged or I'm mis...
# getting-started
n
Hey, is extending sealed classes bugged or I'm missing something ? For example, with this
Copy code
sealed class Foo : Bar() {
    object A : Foo()
}

sealed class Bar {
    object B: Bar()
}
it's totally OK to write this code :
Copy code
val foo: Foo = getFoo()
val baz = when (foo) {
    A -> Unit
}
I would expect
B
to be required in the branches
e
Why?
B
is not a
Foo
s
Your hierarchy is
Bar -> Foo -> A
, right?
n
Worse, the
B
branch is needed only with Bar :
Copy code
val bar: Bar = getBar()
val baz = when (bar) {
    A,
    B -> Unit
}
Why? B is not a Foo
B is a Bar, and Foo extends Bar, so... here comes my confusion ^^
s
Foo and B are both Bars, but that does’t make B a Foo
e
Copy code
Bar
 `- B
 `- Foo
     `- A
n
Here's what I imagined but I can't find a solution with sealed classes :
Copy code
sealed class ASpecific : Common() {
    object A : ASpecific()
}

sealed class BSpecific : Common() {
    object B : BSpecific()
}

sealed class Common {
    object C: Common()
}

class ScreenA {
    fun run(a : ASpecific) {
        when (a) {
            A -> TODO()
            // I would love to be able to treat 'C' there too
        }
    }
}

class ScreenB {
    fun run(b : BSpecific) {
        when (b) {
            B -> TODO()
            // I would love to be able to treat 'C' there too
        }
    }
}
Is it possible to have a "common ancestor" between 2 sealed classes so the "common ancestor" branches should be treated as well as "child" branches ?
e
your hierarchy doesn't make sense even without
sealed
if it were
Copy code
sealed interface Common
sealed interface ASpecific : Common
sealed interface BSpecific : Common
object A : CommonWithA
object B : CommonWithB
object C : CommonWithA, CommonWithB
then both
A is ASpecific
&&
C is ASpecific
(but that naming is rather bad)
n
I get it, I was thinking all inverted 😕 So there's no way to define
SealedClassForScreenA
and
SealedClassForScreenB
that would makes such a code work ?
Copy code
class ScreenA {
    fun run(a: SealedClassForScreenA) {
        when (a) {
            A -> TODO()
            C -> TODO()
        }
    }
}

class ScreenB {
    fun run(b: SealedClassForScreenB) {
        when (b) {
            B -> TODO()
            C -> TODO()
        }
    }
}
e
there is, in my example in the immediately prior message.
n
Yes sorry I meant without C implementing all the other sealed classes ?
I just realised I make no sense with this last sentence, I get it now ^^
e
no. if it doesn't implement them, then it isn't a subtype of them
n
Exactly !
Thanks a lot 🙂