Enum classes

In Kotlin, enum classes are similar to sealed classes, except that all the values of the enum class are the same type. The enum class is useful when the expected outcome is within a small set, such as a small range of colours or the days of the week. Let's create a few examples of enum classes and see how they work:

enum class Color {
RED,
GREEN,
BROWN,
YELLOW
}

The enum keyword is used to declare the enum class. Each value can be declared with a comma-separated list.

Each value of the enum class can be accessed by using the name of the enum class. As we can see in the preceding example, enum Color contains four colors. We can access the name and value of each color using the member name and the ordinal property:

fun main(args: Array<String>) {
println(Color.RED)
println(Color.RED.name)
println(Color.RED.ordinal)
}

The output of this example is as follows:

RED
RED
0

Notice that the output of name is RED and ordinal is 0. This is because each member of the enum class contains a default value, which starts from 0. The default value of green is 1, while brown is 2, and yellow is 3.

We can create an enum type variable using the valueOf function along with the member name in string format. We can access the name and the value using the name and ordinal properties:

fun main(args: Array<String>) {
val color = Color.valueOf("GREEN")
println(color.name)
println(color.ordinal)
}

 It is very important to remember that Kotlin will throw an exception if the valueOf function could not find a name in the enum. In the next section, we will discuss the enum class and constructor. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.217.17