We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 8
o6
Data Types Array String Functions Collections Oops Android Android Stud
Enum Classes in Kotlin
In programming, sometimes there arises a need for a type
to have only certain values. To accomplish this, the
concept of enumeration was introduced. Enumeration is a
named list of constants.
In Kotlin, like many other programming languages, an
enum has its own specialized type, indicating that
something has a number of possible values. Unlike Java
enums, Kotlin enums are classes.
Some important points about enum classes in kotlin —
¢ 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.
Enums are defined by using the enum keyword in front,
class like this:-enum class DAYS{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
Initializing enums —
In Kotlin also enums can have a constructor like Java
enums. Since enum constants are instances of an Enum
class, the constants can be initialized by passing specific
values to the primary constructor.
Here is an example to specify colors to cards —
enum class Cards(val color: String) {
Diamond("black"),Heart("red"),
We can easily access the color of a card using —
val color = Cards.Diamond.color
Enums properties and methods —
As in Java and in other programming languages, Kotlin
enum classes has some inbuilt properties and functions
which can be used by the programmer. Here's a look at
the major properties and methods.
Properties —
1. ordinal: This property stores the ordinal value of the
constant, which is usually a zero-based index.
2. name: This property stores the name of the constant.
Methods —
1. values: This method returns a list of all the constants
defined within the enum class.
2. valueOf: This methods returns the enum constant
defined in enum, matching the input string. If the
constant, is not present in the enum, then an
IllegalArgumentException is thrown.
Example to demonstrate enum class in Kotlin —
enum class DAYS {
SUNDAY,MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
fun main()
// & simple demonstration of properties and methods
for (day in DAYS.values()) {
print1n("${day.ordinal} = ${day.name}")
}
print1n("${DAYS.valueOf(" WEDNESDAY ")}")
Output:
= SUNDAY
= MONDAY
= TUESDAY
WEDNESDAY
= THURSDAY
= FRIDAY
SATURDAY
WEDNESDAY
aAurRUNnNHO
"
Enum class properties and functions —
Since enum class in Kotlin, defines a new type. This class
type can have its own properties and functions. The
properties can be given a default value, however, if not
provided, then each constant should define its own value
for the property. In the case of functions, they are usually
defined within the companion objects so that they do notdepend on specific instances of the class. However, they
can be defined without companion objects also.
Example to demonstrate properties and functions in
Kotlin
// & property with default value provided
enum class DAYS(val isWeekend: Boolean = false){
SUNDAY (true) ,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY ,
FRIDAY,
// Default value overridden
SATURDAY (true) 5
companion object{
fun today(obj: DAYS): Boolean {
return obj.name.compareTo("SATURDAY") == @ || ot
2
main(){
// A simple demonstration of properties and methods
for(day in DAYS.values()) {
printin("${day.ordinal} = ${day.name} and is weekend
}
val today = DAYS.MONDAY;
printin("Is today a weekend ${DAYS.today(today)}")
+
es »
Output:
@ = SUNDAY and is weekend true
1 = MONDAY and is weekend false= TUESDAY and is weekend false
= WEDNESDAY and is weekend false
THURSDAY and is weekend false
= FRIDAY and is weekend false
= SATURDAY and is weekend true
Hau nRwWnD
0
s today a weekend false
Enums as Anonymous Classes —
Enum constants also behaves as anonymous classes by
implementing their own functions along with overriding
the abstract functions of the class. The most important
thing is that each enum constant must be override.
// defining enum class
enum class Seasons(var weather: String) {
Summer ("hot") {
// compile time error if not override the function f
override fun foo() {
printIn("Hot days of a year")
}
Winter("cold"){
override fun foo() {
println("Cold days of a year")
ds
Rainy("moderate"){
override fun foo() {
print1n("Rainy days of a year")
3
abstract fun foo()
}
7/ main function
fun main(args: Array) {
// calling foo() function override be Summer constantSeasons. Summer. F00()
Output:
Hot days of a year
Usage of when expression with enum class —
A great advantage of enum classes in Kotlin comes into
play when they are combined with the when expression.
The advantage is since enum classes restrict the value a
type can take, so when used with the when expression
and the definition for all the constants are provided, then
the need of the else clause is completely eliminated. In
fact, doing so will generate a warning from the compiler.
enum class DAYS{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
fun main(){
when (DAYS. SUNDAY) {
DAYS.SUNDAY -> print1n("Today is Sunday")
DAYS.MONDAY -> println("Today is Monday")
DAYS. TUESDAY -> print1n("Today is Tuesday")
DAYS.WEDNESDAY -> println("Today is Wednesday")
DAYS. THURSDAY -> printin("Today is Thursday")
DAYS.FRIDAY -> println("Today is Friday")DAYS.SATURDAY => printIn("Today is Saturday")
// Adding an else clause will generate a warning
Output:
Today is Sunday
Last Updated : 11 Jul, 2019 12
Previous Next
Kotlin Abstract class Kotlin extension function
Share your thoughts in the
Add Your Comment
comments
Similar Reads
Kotlin Sealed Classes Kotlin Data Classes
Android - Create Group
Kotlin Inline classes BarChart with Kotlin
Hello World program in
Kotlin Data Types Kotlin