juliocbcotta
01/02/2024, 11:40 AMsealed interface Container {
interface Foo : Container
interface Bar : Container
}
In some other package, this is what we can get today
sealed class BaseContainer {
data class FooImpl(val something: Something) : Container.Foo
object BarImpl: Container.Bar
}
With this I can't use BaseContainer
instances as Container
in an exhausting when
without a explicit casting as BaseContainer
can't implement the sealed class Container
.CLOVIS
01/03/2024, 9:02 AMContainer
interface
sealed class BaseContainer : Container { // <-
data class FooImpl(val something: Something) : Container.Foo
object BarImpl: Container.Bar
}
juliocbcotta
01/03/2024, 10:56 AMjuliocbcotta
01/03/2024, 10:57 AMCLOVIS
01/03/2024, 10:58 AMBaseContainer
is in another module?juliocbcotta
01/03/2024, 10:59 AMjuliocbcotta
01/03/2024, 10:59 AMCLOVIS
01/03/2024, 10:59 AMsealed
is about modulesjuliocbcotta
01/03/2024, 11:00 AMNo other subclasses may appear outside the module and package within which the sealed class is defined.
CLOVIS
01/03/2024, 11:02 AMCLOVIS
01/03/2024, 11:03 AMBaseContainer
cannot be a Container
.CLOVIS
01/03/2024, 11:03 AMfun BaseContainer.asContainer(): Container = when (this) {
is BaseContainer.FooImpl -> this
is BaseContainer.BarImpl -> this
}
Of course, it's not as cleanCLOVIS
01/03/2024, 11:07 AMBaseContainer
, that didn't inherit from Container
, and that would break all code elsewhere that relied on Container
Klitos Kyriacou
01/03/2024, 11:18 AMthis
is a BaseContainer
, and therefore it can't be a BaseContatiner.FooImpl
or BarImpl
because those two nested classes are not subclasses of BaseContainer
.Klitos Kyriacou
01/03/2024, 11:24 AMShouldn't a sealed class be able to implement a sealed interface?Yes, indeed it can. As long as it's in the same package.
CLOVIS
01/03/2024, 11:26 AMwhen
, this
is smart-casted to BaseContainer.FooImpl
(or BarImpl
in the other branch), which is a valid value to return when a Container
is expectedKlitos Kyriacou
01/03/2024, 11:37 AMIncompatible types: BaseContainer.FooImpl and BaseContainer
. Which is understandable, as there is no relationship between those two types. It's just like you can't say if (myString is Int)
.
See playgroundCLOVIS
01/03/2024, 1:07 PMFooImpl
and BarImpl
don't implement BaseContainer
. In that case, there is no link whatsoever between them and BaseContainer
.CLOVIS
01/03/2024, 1:10 PMjuliocbcotta
01/03/2024, 1:15 PM