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?
CodePudding user response:
Direction.valueOf("NORTH")
returns value of enum classDirection
by it'sname
. When you callprintln
it implicitly callstoString
method (that every Kotlin object implements implicitly). AndtoString
default implementation forenum class
is enum's name. You can override this method if you want.Direction.NORTH
it's actual enum instance. Like I wrote previouslyprintln
implicitly callstoString
methodDirection.NORTH.name
returnsname
field of typeString
. It is special field, everyenum 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"