Overview

While developing an application, there may arise a situation where we want a variable to have a value out of a given set of allowed values only. The usage and application of enums have also advanced with the evolution of programming languages. In this tutorial, we’ll discuss about Kotlin enums. Like Enum constants are not  just a collections of constants they also have properties, implement interfaces, and much more. In this article we will discuss about enum properties, enum initialization, enum methods, enum functions and many more.

So let’s starts

for example, if we have a variable school, then it should have following values: teacher, class and student.With the help of enum we can achieve this in both java and kotlin.

we can create enum class using enum keyword

enum class DAYS{
  SUNDAY,
  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY,
  SATURDAY
}

Example

fun main() {
    val day=Day.sunday

    val day2=Day2.sunday
    print(day)
    print(day2.num)
    day2.printFormattedDay()

    for (i in Day.values())
    {
        println(i)
    }
}

enum class Day
{
    sunday,
    monday,
    tuesday,
    wednesday,
    thurday,
    friday,
    saturday
}

enum class Day2(val num:Int)
{
    sunday(1),
    monday(2),
    tuesday(3),
    wednesday(4),
    thurday(5),
    friday(6),
    saturday(7);

    fun printFormattedDay()
    {
        println("Days is $this ")
    }
}

Output

sunday1Days is sunday 
sunday
monday
tuesday
wednesday
thurday
friday
saturday

Some key points about enum classes  –

  • Enum constants have properties, methods etc
  • Every enum constants acts as separate instances of the class which is separated by commas.
  • Enum classes increases readability of your code by assigning pre-defined names to constants.
  • Enum class’s instance cannot be created using constructors.

Enum initialization –

Enum classes of kotlin can have a constructor like Java enums. the constants of enums can be initialized by passing specific values to the primary constructor as enum constants are instances of an Enum class

Here is an example  –

enum class Shape(val color: String) {
    Square(“black"),
    Circle(“red"),
}

We can easily access the color of a Shape using –

val color = Cards.Square.color

Enums properties and methods –

Like Java and in other programming languages, Kotlin enum classes has some predefined properties and functions which can be used by the developer. Here are major properties and methods.

Properties –

  1. ordinal: This property contains the ordinal value of the constant, which is a zero-based index.
  2. name: This property contains the name of the constant.

Methods –

  1. values: This method will return a list of all the constants defined within the enum class.
  2. valueOf: This methods will returns the enum constant defined in enum and  matching the input string. If the constant, is not available in the enum, then an IllegalArgumentException is thrown.

Enum class properties and functions –

Since enum class in Kotlin have its own properties and functions. The properties of enum can be given a default value, however, if not provided, then each constant of enums should define its own value for the property. In the case of functions of enums, they are defined within the companion objects because of that they do not depend on specific instances of the class and they can also be defined without companion objects.

Example

// A property with default value provided
enum class DAYS(val isWeekend: Boolean = false){
	SUNDAY(true),
	MONDAY,
	TUESDAY,
	WEDNESDAY,
	THURSDAY,
	FRIDAY,
	// Default value overridden
	SATURDAY(true);

	companion object{
		fun today(obj: DAYS): Boolean {
			return obj.name.compareTo("SATURDAY") == 0 || obj.name.compareTo("SUNDAY") == 0
		}
	}
}

fun main(){
	// A simple demonstration of properties and methods
	for(day in DAYS.values()) {
		println("${day.ordinal} = ${day.name} and is weekend ${day.isWeekend}")
	}
	val today = DAYS.MONDAY;
	println("Is today a weekend ${DAYS.today(today)}")
}

Output:

0 = SUNDAY and is weekend true
1 = MONDAY and is weekend false
2 = TUESDAY and is weekend false
3 = WEDNESDAY and is weekend false
4 = THURSDAY and is weekend false
5 = FRIDAY and is weekend false
6 = SATURDAY and is weekend true
Is today a weekend false

Enums as Anonymous Classes –

Constants of enums in kotlin also act as anonymous classes by implementing their own functions together with overriding the abstract functions of the category. the foremost important thing is that every enum constant must be override.

// defining enum class
enum class Seasons(var weather: String) {
	Summer("hot"){
		// will give compile time error if not override the function foo()
		override fun foo() {			
			println("Hot days of a year")
		}
	},
	Winter("cold"){
		override fun foo() {
			println("Cold days of a year")
		}
	},
	Rainy("moderate"){
		override fun foo() {
			println("Rainy days of a year")
		}
	};
	abstract fun foo()
}
// main function
fun main(args: Array<String>) {
	// calling foo() function override be Summer constant
	Seasons.Summer.foo()
}

Output:

Hot days of a year

Usage of when expression with enum class –

An advantage of enum classes in Kotlin comes when they are used with the when expression.  so when used with the when expression and  all the constants ’s definition are provided, then need of the else clause is fully eliminated. In fact, by doing this will generate a warning from the compiler.

enum class DAYS{
	SUNDAY,
	MONDAY,
	TUESDAY,
	WEDNESDAY,
	THURSDAY,
	FRIDAY,
	SATURDAY;
}

fun main(){
	when(DAYS.SUNDAY){
		DAYS.SUNDAY -> println("Today is Sunday")
		DAYS.MONDAY -> println("Today is Monday")
		DAYS.TUESDAY -> println("Today is Tuesday")
		DAYS.WEDNESDAY -> println("Today is Wednesday")
		DAYS.THURSDAY -> println("Today is Thursday")
		DAYS.FRIDAY -> println("Today is Friday")
		DAYS.SATURDAY -> println("Today is Saturday")
		// Adding an else clause will generate a warning
	}
}

Output:

Today is Sunday

Implementing interfaces in enum classes

An enum class can implement an interface also, which  provide either a single interface members implementation for all of the entries or separate interface members implementation for each entry within its anonymous class. This is done by the adding interfaces to the enum class as follows:

enum class IntArithmetics : BinaryOperator<Int>, IntBinaryOperator {
    PLUS {
        override fun apply(a: Int, b: Int): Int = a+ b
    },
    TIMES {
        override fun apply(a: Int, b: Int): Int = a * b
    };
​
    override fun applyAsInt(a: Int, b: Int) = apply(a, b)
}

Sealed classes in kotlin

Sealed classes in Kotlin are another new concept we didn’t have in Java, and open another new world of possibilities. where an object or a worth can have one in all the kinds from a limited set of values. you’ll consider a sealed class as an extension of enum class. The set of values in enum class is additionally restricted, however an enum constant can have only single instance while a subclass of a sealed class can have multiple instances

Why we need a Sealed class?

Lets first understand the necessity of a sealed class. within the following example we’ve got a category Colorwhich has three subclasses Red, Orange and Blue.

Here the When expression in eval() method must use a else branch else we’ll get a compilation error. Now if we attempt to add a subclass to the category Color, the code within the else branch will execute which may be a default code. The compiler should warn us that the code for the newly added sub class doesn’t exist and thus we must always get a warning or error for adding a new subclass without adding the logic in when expression. This problem is solved using Sealed class.

Sealed classes and when

Sealed classes are mostly used with when statements where  their types and each of the subclasses act as a case. Moreover, we all know that the Sealed class limits the categories. Hence, the else a part of the when statement may be easily removed.

open class Color{
    class Red : Color()
    class Orange : Color()
    class Blue : Color()
}
fun eval(c: Color) =
        when (c) {
            is Color.Red -> println("Paint in Red Color")
            is Color.Orange -> println("Paint in Orange Color")
            is Color.Blue -> println("Paint in Blue Color")
            else -> println("Paint in any Color")
        }
 
fun main(args: Array<String>) {
    val r = Color.Red()
    eval(r)
}

Rules of a Sealed class in Kotlin

  • We cannot create the object of a sealed class which means a sealed class cannot be instantiated.
  • All the subclasses of a sealed class must be declared within the same file where the sealed class is declared.
  • The constructor of sealed class is by default private and we cannot make it non-private.

Implementing Kotlin Sealed Classes

fun main() {
// val  tile=Red("Mushroom",25)
val  tile:Tile=Red("Mushroom",25)
val  tile2=Red("fire",30)
// println("${tile.points}-${tile2.points}")
 
val  points:Int=when(tile)
{
is Blue -> tile.points * 2
is Red -> tile.points*5
}
println(points)
}
 
sealed class Tile
class Red(val type:String, val points:Int):Tile()
class Blue( val points:Int):Tile()

You may also like...

0 Comments

No Comment.