Working with enums
Enums are used when a variable can only take one of a small set of possible values. An example would be the case of type constants (direction: "North", "South", "East", and “West”). With the help of enums, you can avoid errors from passing in invalid constants, and you also document which values are acceptable for use.
In this recipe, we will see how to use enums in Kotlin.
Getting ready
We’ll be using an IntelliJ IDEA for writing and running the code. First, we will be creating a simple type-safe enum, Direction
, with the members NORTH, SOUTH, EAST, and WEST (representing four directions).
How to do it...
Let's see an example of the enum
class:
- In this example, we will create an enum of directions. We will assume that there are only four of them:
enum class Direction { NORTH,SOUTH,EAST,WEST } fun main(args: Array<String>) { var north_direction=Direction.NORTH if(north_direction==Direction.NORTH){ println("Going North") }else{ println("No...