Enum classes

Enumeration types are used to define a set of named constants. Kotlin, same as Java has an enumeration type, the enum class. Let's say that you want to define a type that represents all months in a year. Yes, you could create a normal class with one property, month name, which is of String type. But, then you would have to guard against invalid month name assignments and throw exceptions in such cases. The class would be error-prone and users of your class wouldn't be happy. This is a perfect use case for the enum class, and here is how you would define an enum type to represent all the months of the year:

enum class Month {
JANUARY,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
}

Now you can't have invalid months, and if you want to assign a month type to a variable, you can only choose from the constants we have defined:

val march = Month.MARCH

Enum classes, both in Kotlin and in Java, are full-blown classes, so they can have members, that is, properties and functions. This makes them more powerful than enumeration types in some other languages, C# for example. C#'s enums are value types; by default, the underlying type of each constant is a 32-bit integer and they cannot have members.

We could make our Month enum class more usable; we could also add a numerical representation of each month to the type. Since enum types are classes, they can also have constructors. In fact, Kotlin will allow us to have both primary and secondary constructors and init blocks inside an enum. Here's how you would add a property of Int type to our enum class that represents Month numerically:

enum class Month2 (val num: Int) {
JANUARY(1),
FEBRUARY(2),
MARCH(3),
APRIL(4),
MAY(5),
JUNE(6),
JULY(7),
AUGUST(8),
SEPTEMBER(9),
OCTOBER(10),
NOVEMBER(11),
DECEMBER(12)
}

This integer constructor property is only needed when defining a constant inside this enum. You would then assign a Month enum constant like in the previous example. And, when you have an actual constant, from it you can access all the members that enum type defines. Here's how you would access the numerical representation of our Month enum:

val may = Month2.MAY
val mayNum = may.num

The enum class type also has two helper methods. The first one is for getting an array of all defined constants. We use it here to print out all the months:

for (month in Month.values()) {
println(month)
}

The second one is for getting an enum object from the constant string value. This is how we would get the month of June, by passing a string to the valueOf function:

val june = Month.valueOf("JUNE")
..................Content has been hidden....................

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