You are here
Home > Kotlin

Kotlin: Enum Class

Enum Class

Kotlin: Enum Class

In this post we will discuss Enum Class in kotlin.

  • Enumeration is a special type of class, if class is enum type then it is limited to a set of predefined constants.
  • To declare a class as enum use enum keyword before the class

Example:

enum class Direction
{
North,South,West,East
}
fun main(args:Array<String>)
{
var e=Direction.East;
if(e==Direction.North)
{
println(“this is north direction”);
}
else
{
println(“I don’t know direction”);
}

}
output:

Explanation:
In above example, we create a Direction enum class and in main function we create object of Direction class with East member. We check direction class member is equal to north it returns false because we created an object of East member.

  • Same as all other classes the enum class also extends classes and implements interfaces.

Example:

interface displayable
{
fun display():Unit
}
public enum class Directions:displayable
{
North{
override fun display() {
println(“Direction is North”);
}
},
South{
override fun display() {
println(“Direction is South”);
}
},
East{
override fun display() {
println(“Direction is East”);
}
},
West{
override fun display() {
println(“Direction is West”);
}
}
}
fun main(args:Array<String>)
{
val d=Directions.North;
d.display();
}
 output:

Explanation:
In above example, we create displayable interface with display function. We implement this interface into enum class and create a member of this class. We have to override display method for each member of the enum class.

You can also by SQL 70-761 book write by me from Amazon.
You can also by Kotlin Book write by me from Amazon.

Microsoft SQL 70-762 Practice Test.

Microsoft MCSA 70-761 Practice Test:

Leave a Reply

Top