sayang_android
sayang_android

Reputation: 314

Difference between enum class method in Kotlin for calling constant name

Im new in kotlin, i was trying enum class and i found that these 3 method return the same thing.

package com.example.test1

fun main() {
    println(Direction.valueOf("NORTH")) // print NORTH
    println(Direction.NORTH)            // print NORTH
    println(Direction.NORTH.name)       // print NORTH
}

enum class Direction(var direction: String, var distance: Int) {
    NORTH("North", 20),
    SOUTH("South", 30),
    EAST("East", 10),
    WEST("West", 15);
}

What is the difference uses between them?

Upvotes: 2

Views: 489

Answers (1)

Evgeny K
Evgeny K

Reputation: 3147

  • Direction.valueOf("NORTH") returns value of enum class Direction by it's name. When you call println it implicitly calls toString method (that every Kotlin object implements implicitly). And toString default implementation for enum class is enum's name. You can override this method if you want.

  • Direction.NORTH it's actual enum instance. Like I wrote previously println implicitly calls toString method

  • Direction.NORTH.name returns name field of type String. It is special field, every enum class has, that returns it's name

For example if you change enum class like this:

enum class Direction(var direction: String, var distance: Int) {
    NORTH("North", 20),
    SOUTH("South", 30),
    EAST("East", 10),
    WEST("West", 15);

    override fun toString(): String {
        return this.name.lowercase()
    }
}

first two prints will be "north"

Upvotes: 2

Related Questions