Enum Class trong Kotlin
1. Giới thiệu
Enum class đại diện cho một tập hợp cố định các giá trị hằng số.
2. Khai báo cơ bản
enum class Color {
RED, GREEN, BLUE
}
fun main() {
val color = Color.RED
println(color) // RED
println(color.name) // RED
println(color.ordinal) // 0
}3. Enum với Properties
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}
fun main() {
println(Color.RED.rgb) // 16711680
println(Color.RED.rgb.toString(16)) // ff0000
}4. Enum với nhiều Properties
enum class Planet(
val mass: Double, // kg
val radius: Double // m
) {
MERCURY(3.303e23, 2.4397e6),
VENUS(4.869e24, 6.0518e6),
EARTH(5.976e24, 6.37814e6),
MARS(6.421e23, 3.3972e6);
val surfaceGravity: Double
get() = 6.67300E-11 * mass / (radius * radius)
}5. Enum với Methods
enum class Operation {
ADD {
override fun apply(a: Int, b: Int) = a + b
},
SUBTRACT {
override fun apply(a: Int, b: Int) = a - b
},
MULTIPLY {
override fun apply(a: Int, b: Int) = a * b
};
abstract fun apply(a: Int, b: Int): Int
}
fun main() {
println(Operation.ADD.apply(5, 3)) // 8
println(Operation.MULTIPLY.apply(5, 3)) // 15
}6. Enum trong when
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
fun describe(dir: Direction) = when (dir) {
Direction.NORTH -> "Going up"
Direction.SOUTH -> "Going down"
Direction.EAST -> "Going right"
Direction.WEST -> "Going left"
}7. Enum methods và properties
enum class Color {
RED, GREEN, BLUE
}
fun main() {
// Lấy tất cả values
val colors = Color.values()
colors.forEach { println(it) }
// Parse từ string
val color = Color.valueOf("RED")
println(color) // RED
// entries (Kotlin 1.9+)
Color.entries.forEach { println(it) }
}8. Enum implement Interface
interface Printable {
fun print()
}
enum class Status : Printable {
PENDING {
override fun print() = println("⏳ Pending...")
},
APPROVED {
override fun print() = println("✅ Approved!")
},
REJECTED {
override fun print() = println("❌ Rejected!")
}
}
fun main() {
Status.APPROVED.print()
}9. Ví dụ thực tế
enum class HttpStatus(val code: Int, val description: String) {
OK(200, "Success"),
CREATED(201, "Created"),
BAD_REQUEST(400, "Bad Request"),
UNAUTHORIZED(401, "Unauthorized"),
NOT_FOUND(404, "Not Found"),
SERVER_ERROR(500, "Internal Server Error");
companion object {
fun fromCode(code: Int): HttpStatus? {
return entries.find { it.code == code }
}
}
}
fun main() {
val status = HttpStatus.fromCode(404)
println(status?.description) // Not Found
}10. So sánh với Sealed Class
// Enum - instances cố định, giống nhau
enum class Simple { A, B, C }
// Sealed - có thể có data khác nhau
sealed class Rich {
data class WithData(val x: Int) : Rich()
object NoData : Rich()
}📝 Tóm tắt
enum classcho tập hợp hằng số cố định.namevà.ordinalcó sẵn- Có thể có properties và methods
values()lấy tất cả enum valuesvalueOf("NAME")parse từ stringwhenexhaustive với enum
Last updated on