https://kotlinlang.org logo
#announcements
Title
# announcements
x

xii

03/04/2021, 12:54 PM
is it possible to create a sub enum class from an enum class?
so lets say you have enum class
Copy code
enum class Test{
a,
b,
c}
and you create a function that accepts Test enum class as parameter
but you only want a and b to be passable to it, not c
how would one write this?
r

Rob Elliot

03/04/2021, 1:04 PM
I think sealed interfaces in kotlin 1.5 may allow you to write this:
Copy code
sealed interface Allowed
sealed class Test {
    object a : Test(), Allowed
    object b : Test(), Allowed
    object c : Test()
}

fun onlyAllowed(foo: Allowed): Unit = TODO()

// compiles
onlyAllowed(Test.a)
onlyAllowed(Test.b)

// does not compile
onlyAllowed(Test.c)
Actually this will work in kotlin 1.4:
Copy code
sealed class Test {
    sealed class Allowed : Test() {
        object a : Allowed()
        object b : Allowed()
    }
    object c : Test()
}
x

xii

03/04/2021, 2:05 PM
interesting, i'll give it a try
thank you!
i think you cannot do that with enum classes, only sealed, right?
r

Rob Elliot

03/04/2021, 2:08 PM
As far as I know
23 Views