Kotlin Enum Classes: Power Up Constants in 2025! 🚀
Here’s an enum with a constructor:
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
} // Colors with RGB values 🎨
Enum Basics:
- 📋 Defines a fixed set of constants.
- 🔧 Can hold data via constructors.
- ⚡ Each constant is an instance of the enum class.
Functions and Properties in Enums 🛠️
Enums can have properties and functions—just add a semicolon (;) after the last constant if members follow. Abstract members require implementation by each constant.
enum class Color {
RED {
override val rgb: Int = 0xFF0000
},
GREEN {
override val rgb: Int = 0x00FF00
},
BLUE {
override val rgb: Int = 0x0000FF
};
abstract val rgb: Int
fun colorString() = "#%06X".format(0xFFFFFF and rgb) // Hex string maker
}
fun main() {
println(Color.RED.colorString()) // Outputs: #FF0000
}
Member Magic:
- 🧰 Add properties and methods like any class.
- 📝 Semicolon separates constants from members.
- 🔧 Abstract members enforce constant-specific logic.
Simple Enum 🌈
A basic enum is just a list of constants—each an object, split by commas:
enum class Color {
RED, GREEN, BLUE // Simple and sweet!
}
Simple Perks:
- 📋 Lightweight way to group constants.
- ⚡ No extra baggage—just names.
- ✅ Still fully-fledged objects.
Mutability 🔄
Enums can be mutable, acting like singletons with changeable state:
enum class Planet(var population: Int = 0) {
EARTH(7 * 100000000),
MARS();
override fun toString() = "$name[population=$population]"
}
fun main() {
println(Planet.MARS) // MARS[population=0]
Planet.MARS.population = 3
println(Planet.MARS) // MARS[population=3] 🌍
}
Mutable Might:
- 🔄 Change state with var properties.
- 📦 Singleton-like behavior per constant.
- ⚡ Flexible for dynamic data.
Enum with Companion Object 🧩
Add a companion object for shared utilities or factory methods:
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF);
companion object {
fun fromRgb(rgb: Int) = values().find { it.rgb == rgb } ?: BLUE
}
}
fun main() {
println(Color.fromRgb(0xFF0000)) // Outputs: RED
}
Companion Tricks:
- 🧩 Shared logic via companion object.
- 🔍 Find constants with custom methods.
- ⚡ Enhances enum usability.
Using Enums in When Expressions 🤝
Enums pair perfectly with when for concise logic:
fun main() {
val color = Color.RED
val message = when (color) {
Color.RED -> "Hot!"
Color.GREEN -> "Cool!"
Color.BLUE -> "Calm!"
}
println(message) // Outputs: Hot!
}
enum class Color {
RED, GREEN, BLUE
}
When Wins:
- 🤝 Matches enums cleanly in when.
- ⚡ Exhaustive checks with no else needed.
- 🔍 Leverages enum constants for logic.
..
Comments
Post a Comment