Skip to content

Instantly share code, notes, and snippets.

@kalaiselvan369
Last active June 12, 2023 11:40
Show Gist options
  • Save kalaiselvan369/9c9092fec8d4f41630a40b40dea323f0 to your computer and use it in GitHub Desktop.
Save kalaiselvan369/9c9092fec8d4f41630a40b40dea323f0 to your computer and use it in GitHub Desktop.
Enumeration in kotlin
package enumerations
fun main() {
val east = Direction.EAST
println(east.notation)
println(east.oppositeDirection())
//println(east.opposite()) // not possible, you cannot invoke extension function declared inside class
east.westOpposite()
}
enum class Direction(val notation: Char) {
EAST('E'),
WEST('W'),
NORTH('N'),
SOUTH('S');
// declaring extension function inside enum class.
// we cannot invoke this function outside the class at all
fun Direction.opposite() =
when(this) {
EAST -> WEST
WEST -> EAST
NORTH -> SOUTH
SOUTH -> NORTH
}
fun westOpposite() {
println(WEST.opposite())
}
}
fun Direction.oppositeDirection() =
when(this) {
Direction.EAST -> Direction.WEST
Direction.WEST -> Direction.EAST
Direction.NORTH -> Direction.SOUTH
Direction.SOUTH -> Direction.NORTH
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment