Off the top of my head, this compiles and may be w...
# announcements
s
Off the top of my head, this compiles and may be what you’re looking for—
Copy code
sealed class OutsideGroup {
    class Option1: OutsideGroup()
    class Option2: OutsideGroup()

    sealed class InsideGroup: OutsideGroup() {
        class Option3: InsideGroup()
        class Option4: InsideGroup()
    }
}

fun returnOuter(): OutsideGroup = OutsideGroup.Option1()

fun returnInner(): OutsideGroup.InsideGroup = OutsideGroup.InsideGroup.Option3()
You could also flatten out the sealed class members:
Copy code
sealed class OutsideGroup
sealed class InsideGroup: OutsideGroup()
class Option1: OutsideGroup()
class Option2: OutsideGroup()
class Option3: InsideGroup()
class Option4: InsideGroup()

fun returnOuter(): OutsideGroup = Option1()
fun returnInner(): InsideGroup = Option3()
a
use
òbject
instead of
class
in this example, there is no need for multiple instances
s
true, this example assumes that you’d be filling it in with parameters
Here’s an updated example:
Copy code
sealed class OutsideGroup
sealed class InsideGroup: OutsideGroup()
object Option1: OutsideGroup()
object Option2: OutsideGroup()
object Option3: InsideGroup()
object Option4: InsideGroup()

fun returnOuter(): OutsideGroup = Option1
fun returnInner(): InsideGroup = Option3
fun returnInnerFromOuter(): OutsideGroup = Option4
fun returnOuterFromInner(): InsideGroup = Option2   // Fails
t
Thanks I will consider that. Unfortunately it is still not possible (afaik) to flatten nested sealed classes which will pose a problem with naming. But what if the two deriving classes each may only return non-disjoint subsets of the enum? The method above wouldn't work anymore, since the elements in the intersection can not extend two sealed classes at the same time
a
@tschuchort can you give us an example of the desired hierarchy?
t
something like this:
Copy code
interface Interf {
   fun foo(): A|B|C
}

class X : Interf {
   override fun foo(): A|B
}

class Y : Interf {
   override fun foo(): B|C
}
a
the only way I can think of is using a sealed class + an interface
t
How would you do it?
a
actually you'd need two interfaces + a sealed class (or just 3 interfaces), but not sure if its worth it (no when-exhaustiveness for
Return2
or
Interf.foo()
)
Copy code
interface Base { }

sealed class Return1: Base
interface Return2: Base

object A : Return1()
object B : Return1(), Return2
object C: Return2

interface Interf {
   fun foo(): Base
}

class X : Interf {
   override fun foo(): Return1
}

class Y : Interf {
   override fun foo(): Return2
}