alwaysday1
alwaysday1

Reputation: 1783

Is it possible to nest an enum contains class's properties within an open class?

I've read this thread, it doesn't address my specific case.

Here's my minimal case:

open class BaseCase() {
    lateinit var txtNode: UiObject

    enum class TextType(val field: UiObject) {
        PlainText(txtNode)
    }
}

But there's error:

enter image description here

I was wondering if it is possible in Kotlin?

Upvotes: 0

Views: 100

Answers (2)

Mohmmaed-Amleh
Mohmmaed-Amleh

Reputation: 438

that's because enum class are final static classes ---> you cannot access non static variables. for testing -> if you move your variable to companion object the code will work

Upvotes: 0

Ivo
Ivo

Reputation: 23164

The problem is that txtNode is an instance variable. Different BaseCase instances could have different values. So the enum cannot know which one of them to take.

Let's for simplicity say txtNode is a String instead of an UiObject

Then how would the following code work?

val a = BaseCase()
a.txtNode = "test"
val b = BaseCase()
b.txtNode = "test2"
val c = BaseCase.TextType.PlainText

would c have "test" or "test2" as field? It simply isn't possible.

Upvotes: 2

Related Questions