1

I have enum class with method declared inside

enum class MyEnum {
    VAL1, VAL2, VAL3;

    fun myFunc(): Any{
         // Here I want to access selected value
         // VAL1 in my example
    }
}

I can call this method like this

MyEnum.VAL1.myFunc()

But is it possible inside myFunc to get the value method was called on? In my example it's VAL1.

1
  • 3
    You can use this? What's the context of referencing self? If it's to return some value based on "selected" value with a switch (when), then it's better to have a field in the enum and just return its value. Commented Jul 10, 2018 at 19:01

2 Answers 2

5

You can use this and this.ordinal which returns the ordinal of this enumeration constant
Also if you do this:

fun myFunc(): Any{
    val array = MyEnum.values()
    println(array[this.ordinal])
    println(this)
    return array[this.ordinal]
}

and call MyEnum.VAL2.myFunc() you will see VAL2

Sign up to request clarification or add additional context in comments.

Comments

1

Try as follow

enum class MyEnum {
    VAL1 {
        override fun myFunc() {
            //do something with VAL1 using this
        }
    },
    VAL2 {
        override fun myFunc() {
            //do something with VAL2 using this
        }
    },
    VAL3 {
        override fun myFunc() {
            //do something with VAL3 using this
        }
    };

    abstract fun myFunc()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.