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 classDirectionby it'sname. When you callprintlnit implicitly callstoStringmethod (that every Kotlin object implements implicitly). AndtoStringdefault implementation forenum classis enum's name. You can override this method if you want.Direction.NORTHit's actual enum instance. Like I wrote previouslyprintlnimplicitly callstoStringmethodDirection.NORTH.namereturnsnamefield of typeString. It is special field, everyenum classhas, 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"
