Hanbit the Developer

Kotlin Documentation | Enum classes 본문

Mobile/Kotlin

Kotlin Documentation | Enum classes

hanbikan 2023. 5. 23. 15:26

Kotlin Documentation 시리즈에 대해

Category: Concepts - Classes and objects

문서 링크: https://kotlinlang.org/docs/enum-classes.html


enum constant는 오브젝트이며 컨마로 구분한다.

enum class Direction {
    NORTH, SOUTH, WEST, EAST
}

각각의 enum은 enum 클래스의 인스턴스이다.

enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)
}

Anonymous classes

enum class ProtocolState {
    WAITING {
        override fun signal() = TALKING
    },

    TALKING {
        override fun signal() = WAITING
    };

    abstract fun signal(): ProtocolState
}

Implementing interfaces in enum classes

enum class IntArithmetics : BinaryOperator<Int>, IntBinaryOperator {
    PLUS {
        override fun apply(t: Int, u: Int): Int = t + u
    },
    TIMES {
        override fun apply(t: Int, u: Int): Int = t * u
    };

    override fun applyAsInt(t: Int, u: Int) = apply(t, u)
}

vs Sealed class

  • Enum에서는 특정 값을 single instance로서 하나의 객체만 제한적으로 사용할 수 있으며, 생성자의 형태도 동일해야만 한다.
  • Sealed에서는 state을 포함하고 있는 여러 개의 instance를 가질 수 있고, 생성자도 각각의 특징에 따라서 다르게 가져갈 수 있다. ⇒ 정적인 아닌 다양한 state를 사용할 수 있다.

Working with enum constants

EnumClass.valueOf(value: String): EnumClass
EnumClass.values(): Array<EnumClass>

Usages

enum class RGB { RED, GREEN, BLUE }

fun main() {
    for (color in RGB.values()) println(color.toString()) // prints RED, GREEN, BLUE
    println("The first color is: ${RGB.valueOf("RED")}") // prints "The first color is: RED"
}
  • RGB.values(): Array<RGB>
  • RGB.valueOf(”RED”): RGB.RED
enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)
}
  • Color.RED.name, Color.RED.toString(): “RED”
  • Color.RED.rgb: 0xFF0000
  • Color.RED.ordinal: 0

+enumValues(), entries