Last active
June 12, 2023 11:40
-
-
Save kalaiselvan369/9c9092fec8d4f41630a40b40dea323f0 to your computer and use it in GitHub Desktop.
Enumeration in kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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