Let’s have a look at enums in kotlin. Unlike Java, where enum
is a Type; in Kotlin, enums are classes
Defining an enum¶
1
2
3
| enum class Direction {
NORTH, SOUTH, WEST, EAST
}
|
Defining an enum with a variable¶
1
2
3
| enum class Direction(val shortName: Char) {
NORTH('N'), SOUTH('S'), WEST('W'), EAST('E')
}
|
Template Method pattern in Enum¶
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| enum class Direction(val shortName: Char) {
NORTH('N') {
override fun move() = "Moving in North Direction"
},
SOUTH('S') {
override fun move() = "Moving in South Direction"
},
WEST('W'){
override fun move() = "Moving in West Direction"
},
EAST('E'){
override fun move() = "Moving in East Direction"
};
abstract fun move(): String
}
|
Companion methods in enum¶
1
2
3
4
5
6
7
| enum class Direction(val shortName: String) {
NORTH("N"), SOUTH("S"), WEST("W"), EAST("E");
companion object {
fun valueOfIgnoreCase(name: String) = valueOf(name.uppercase(Locale.getDefault()))
fun valueOfShortName(shortName: String): Direction? = Direction.values().find { it.shortName == shortName }
}
}
|
Links¶