Kotlin Enum Classes

Kotlin Enum Classes

Kotlin Enum – Enum is a special data type that allows a variable to hold a value only from a set of predefined constants.

In this tutorial, we shall learn about Kotlin Enum Class : Syntax, Initialization, how enum classes are different from regular classes. An example program is provided to demonstrate the usage of Kotlin Enum.

Syntax

Following is the syntax to define an Enum class in Kotlin

enum class<enum_class_name> {constant1,constant2,constant3}

Any number of constants could be specified inside the class separated by comma. Each Enum constant is implicitly an Object of type <enum_class_name>.

Following is an example of defining a Kotlin Enum class “MobileColor” :

1

2

3

4

5

enumclassMobileColor{

GOLD,SILVER,WHITE,BLACK,RED

}

Kotlin Enum Initialization

As Kotlin Enum is an object of an Enum class, these could be initialized. We shall use the same example of MobileColor enum class to demonstrate the initialization of enums.

1

2

3

4

5

6

7

8

9

enumclassMobileColor(val value:Int){

GOLD(0xffd323),

SILVER(0xeaeaea),

WHITE(0xffffff),

BLACK(0x000000),

RED(0xFF0000)

}

Kotlin Enum Example – To demonstrate the usage of Enum Classes

Following example demonstrates the usage of enum class MobileColor. Data Class, Mobile, has a variable as Enum class, MobileColor Object.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

/**

* Kotlin Example to Enum Classes in Kotlin

*/

fun main(args:Array<String>){

val mobile1:Mobile=Mobile("IPhone",MobileColor.GOLD)

val mobile2:Mobile=Mobile("SONY",MobileColor.BLACK)

// access enum variables

println("The color of my "+mobile1.name+" is "+mobile1.color)

println("The color of my "+mobile2.name+" is "+mobile2.color)

// access the value of the variable in Enum Object

println(mobile1.color.toString()+" value is "+mobile1.color.value)

println(mobile2.color.toString()+" value is "+mobile2.color.value)

}

data classMobile(val name:String,val color:MobileColor)

enumclassMobileColor(val value:Int){

GOLD(0xffd323),

SILVER(0xeaeaea),

WHITE(0xffffff),

BLACK(0x000000),

RED(0xFF0000)

}

1

2

3

4

5

6

The color of my IPhone isGOLD

The color of my SONY isBLACK

GOLD value is16765731

BLACK value is0

How enum class is different from a regular class

You cannot create new instances of an Enum class outside of its definition. In other words outside enum definition, you cannot create an object of type Enum Class by passing values to its primary constructor. You may do so for regular classes.

Conclusion :

In this Kotlin Tutorial – Kotlin Enum Classes, we have learnt the syntax and usage with help of an Example program.