The most basic usage of enum classes is implementing type-safe enums:
enum class Direction {
NORTH, SOUTH, WEST, EAST
}
Each enum constant is an object. Enum constants are separated with commas.
Initialization
Since each enum is an instance of the enum class, they can be initialized as:
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}
Enum Constants as Anonymous Classes
Enum constants can also declare their own anonymous classes:
package net.javaguides.kotlin.examples
enum class CardType {
SILVER {
override fun calculateCashbackPercent() = 0.25 f
},
GOLD {
override fun calculateCashbackPercent() = 0.5 f
},
PLATINUM {
override fun calculateCashbackPercent() = 0.75 f
};
abstract fun calculateCashbackPercent(): Float
}
fun main(args: Array < String > ) {
val cashbackPercent = CardType.SILVER.calculateCashbackPercent();
println(cashbackPercent);
}
Output:
0.25
Enums Implementing Interfaces
package net.javaguides.kotlin.examples
interface ICardLimit {
fun getCreditLimit(): Int
}
enum class CardType: ICardLimit {
SILVER {
override fun getCreditLimit() = 100000
},
GOLD {
override fun getCreditLimit() = 200000
},
PLATINUM {
override fun getCreditLimit() = 300000
}
}
fun main(args: Array < String > ) {
val creditLimit = CardType.PLATINUM.getCreditLimit()
println(creditLimit);
}
Output:
300000
Comments
Post a Comment