Enum

In computer programming, an enumerated type (also called enumeration, enum) is a data type consisting of a set of named  values called elements, members, enumeral, or enumerators of  the type. In Kotlin, like many other programming languages, an enum has its own specialized type, indicating that something has a number of possible values. Kotlin enums are classes.

  • Enum constants aren’t just mere collections of constants, these have properties, methods etc
  • Each of the enum constants acts as separate instances of the class and separated by commas
  • Enums increases readability of your code by assigning pre- defined names to constants
  • An instance of enum class cannot be created using constructors

Syntax to define enum class

An enum class with name enum_class_name will defined that contains three constants contant1, constant2 and constant3. Note that each constant is separated by comma. Similarly, you can add any number of constants in this class.

Initialization

Here, I have initialized January with “JAN”, February with “FEB” and March with “MAR”. We can easily access the color of a card using.


Jan
Shorthand changed to J.
Enums as Anonymous classes

Second month of the year.
Hello, Kotlin Enums

Enum constants can behave as anonymous classes be implementing their own functions along with overriding base functions from the class as shown below.

Enum inside an Enum
 
Tuesday

It’s possible to define another enum class in the current enum class as shown below. Only an enum class can invoke another one. The inner class Day cannot be invoked from the enum constants.  

Questions

I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂

 


 

Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published. Required fields are marked *