Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to nest an enum within a data class in Kotlin?

Is there a way to nest an enum within a data class in Kotlin?

data class D(val a:Any) {
    enum class E {F,G}
    ...
}

Or to declare it inline within a function?

fun foo() {
    enum class E {F,G}
    doSomething()
}

I can't find documentation on the rules for where enums are allowed to be declared.

like image 271
Julian A. Avatar asked Jul 04 '17 17:07

Julian A.


1 Answers

Yes, you can nest the enum in a data class, but not in a function:

data class Outer(val a: InnerEnum) {
    enum class InnerEnum { A, B }
}

fun foo() {
    val o = Outer(Outer.InnerEnum.A)
    println(o) // --> Outer(a=A)
}
like image 127
guenhter Avatar answered Jan 04 '23 03:01

guenhter