Introduction
An enum class helps you group related constant values under one name. It makes your code easier to read and use.
An enum class helps you group related constant values under one name. It makes your code easier to read and use.
enum class EnumName { CONSTANT1, CONSTANT2, CONSTANT3 }
Each constant is written in uppercase by convention.
You can add properties and functions inside the enum class if needed.
enum class Direction { NORTH, SOUTH, EAST, WEST }
enum class Light { RED, YELLOW, GREEN }
enum class Day(val isWeekend: Boolean) { MONDAY(false), TUESDAY(false), WEDNESDAY(false), THURSDAY(false), FRIDAY(false), SATURDAY(true), SUNDAY(true) }
This program declares an enum for seasons and prints the current one.
enum class Season { SPRING, SUMMER, FALL, WINTER } fun main() { val current = Season.SUMMER println("Current season is $current") }
Enum constants are objects and can have their own properties and methods.
You can use enums in when expressions for clear and safe branching.
Enum classes group fixed sets of constants under one type.
They improve code clarity and safety by replacing magic numbers or strings.
You can add properties and functions to enum constants for extra behavior.
enum class in Kotlin?Direction with constants NORTH, SOUTH, EAST, and WEST?enum class followed by the name and curly braces containing constants separated by commas.enum class Color { RED, GREEN, BLUE }
fun main() {
val c = Color.GREEN
println(c.name)
}name property that returns its exact name as a string.c.name where c is Color.GREEN, so it prints "GREEN" exactly as declared.enum class Size {
SMALL,
MEDIUM
LARGE
}MEDIUM is missing a comma after it.rgb to an enum class Color that stores the color's RGB integer value, and access it for Color.RED? Choose the correct code snippet.val rgb: Int in constructor and assigns values. enum class Color { RED = 0xFF0000, GREEN = 0x00FF00, BLUE = 0x0000FF }
fun main() { println(Color.RED.rgb) } uses invalid assignment syntax. enum class Color { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF) }
fun main() { println(Color.RED.rgb) } misses constructor declaration. enum class Color { RED, GREEN, BLUE }
fun main() { println(Color.RED.rgb) } has no property defined.Pass the test and this pattern moves unknown