The Programmers Guide To Kotlin - Enums & Sealed Classes
Written by Mike James   
Monday, 26 August 2019
Article Index
The Programmers Guide To Kotlin - Enums & Sealed Classes
An Example & Sealed Classes

Kotlin provides enums just like Java but you need to keep in mind how they are implemented if you are to understand how to use them. As an alternative you can use sealed classes but are these really better than an enum? In this extract from the book on Kotlin by Mike James we look at how to work with and understand enums and sealed classes.

 

Programmer's Guide To Kotlin Second Edition

kotlin2e360

You can buy it from: Amazon

Contents

  1. What makes Kotlin Special
  2. The Basics:Variables,Primitive Types and Functions 
  3. Control
         Extract: If and When 
  4. Strings and Arrays
  5. The Class & The Object
  6. Inheritance
  7. The Type Hierarchy
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
        Extract: Iterators & Sequences 
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
        Extract: Destructuring 
  13. Exceptions, Annotations & Reflection
  14. Coroutines
        Extract: Coroutines 
  15. Working with Java
        Extract: Using Swing ***NEW!

<ASIN:B096MZY7JM>

This chapter is about the new features that Kotlin supports to make working with data within a program easier. It isn't about database or file access, which are both largely unchanged from Java. This is about some of the lower level approaches to make representing data within your programs easier and clearer.

Sections not included in this extract:

  • Data Classes
  • Equality

Enums

Enums or enumerations are a way of creating ordinal data types.

That is, an ordinal data type is one that is essentially a set of named integer values. For example, a classic use of enum is to represent the days of the week as something that looks like a set of named constants Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday instead of 0,1,2,3,4,5,6. Behind the scenes of an enum there are a set of integers which identify the particular constant and provide an order relation. That is Monday<Tuesday because 0<1. The integer associated with an enum is generally called its ordinal or ordinal position.

In both Java and Kotlin, but not in many other languages, the enum data type is a class and this provides lots of additional features and possibilities. You declare an enum class by putting the enum modifier in front of a fairly standard class declaration:

enum class Days{Monday, Tuesday, Wednesday, Thursday, 
                            Friday, Saturday, Sunday}

Notice that the enumeration of names is presented as if it was the body of the class being defined and in a sense it is. Each of the names is converted into a property of the Days enum class which in turn behaves like a static class and a type.

For example to declare a variable suitable for holding values from the enumeration you would use:

var myDay:Days

and to store a value in myDay:

myDay=Days.Monday

You can use an enum in conditionals and when statements to make your code more readable. For example:

var myDay:Days=Days.Monday     
if(myDay==Days.Monday)

If myDay is of type Days what type is Days.Monday?

The answer is that it is of type Days as well. The peculiar thing about an enum is that it is a static class that has properties that are instances of the same type. This observation is the key to understanding, and getting the most out, of enums.

The instances of the enum come with few standard methods, the most important of which are name and ordinal. As you can guess, name returns the string that is the name of the instance, and ordinal, an integer indicating its position in the enumeration sequence.

Notice that there is only one instance of each of the enum classes and this is shared between all of the variables that make use of it. That is:

var myDay=Days.Monday

and:

var yourDay=Days.Monday

both reference the same instance of Days i.e. Days.Monday. This can be important to know if you extend the enum class.

As Kotlin allows an enum class to be declared with properties and methods just like any other class, you can now see that you can extend what an enum can do.

For example, we can add a method to each of the days of the week to indicate if it is working or non-working. However, we have a small syntax problem. How do you indicate when the list of enum properties has ended and the rest of the class declaration starts? The Kotlin answer is that you use a single semicolon to mark the two sections:

enum class Days {Monday, Tuesday, Wednesday, Thursday,
                Friday, Saturday, Sunday
;   fun isWorking() {
  if (this.name == "Saturday" || this.name == "Sunday"){
    println("non-working")
  } else {
    println("working")
  } }
}

With this definition each of the enum properties has a new method isWorking:

var myDay: Days = Days.Saturday
myDay.isWorking()

which prints non-working.

Notice that this method is an instance method and not part of the static myDays object. This, however, does have some predefined methods:

  • values – returns an array of all of the enum values

For example:

println(Days.values()[1].name)

displays "Tuesday".

  • valuesOf(string) - returns the enum object that has a name that exactly matches the string

For example:

println(Days.valueOf("Monday").ordinal)

prints 0

Not only can you add methods and properties to each instance, you can also define a constructor.



Last Updated ( Monday, 26 August 2019 )