Junior — Middle
Mis on enum class kasutamise eesmärk Kotlinis ja kuidas see erineb tavalisest loendist?
sobes.tech AI
Vastus AI-lt
In Kotlin, enum class is used to define a limited set of constants, each of which is an object of the class. Unlike regular enumerations in other languages, Kotlin enum classes can contain properties, methods, and implement interfaces.
Main differences:
- Each constant is an instance of the enum class, with the ability to have unique properties and behaviors.
- Constructors and methods can be added.
- Interface inheritance is supported.
Example:
enum class Direction(val degrees: Int) {
NORTH(0),
EAST(90),
SOUTH(180),
WEST(270);
fun description() = "Direction $name with an angle of $degrees degrees"
}
fun main() {
println(Direction.NORTH.description()) // Direction NORTH with an angle of 0 degrees
}
Therefore, enum class in Kotlin is a powerful tool for working with a set of related constants with additional logic.