Kotlin/Kotlin In Action

[Kotlin] 2-3. 선택 표현과 처리 : enum과 when

gudwnsgur 2022. 5. 15. 17:46
728x90

[ enum 클래스 정의 ]

// 가장 기본적인 enum class
enum class Color {
	RED, BLUE, YELLOW, GREEN, BLACK
}

 

enum 클래스 안에 프로퍼티나 메서드를 정의할 수 있다.

enum class Color(
	val r: Int, val g: Int, val b: Int
) {
	RED(255, 0, 0),
	YELLOW(255, 255, 0),
	GREEN(0, 255, 0),
	BLUE(0, 0, 255)
	;

	// enum class 내부 메서드
	fun getRgb(): Int {
		return (r * 256 + g) * 256 + b
	}
	// fun getRgb() = (r * 256 + g) * 256 + b
}

 

enum의 각 상수를 정의할 때 그 상수에 해당하는 프로퍼티 값을 지정해야 한다. RED x , RED(255,0,0) o

enum class 내부에 메서드를 정의할 때 ; 을 필수적으로 붙여야 한다.


[ when으로 enum 클래스 다루기 ]

코틀린의 when은 자바의 switch를 대체할 수 있다.

fun getColor(color: Color) =
    when(color) {
    	Color.RED -> "빨강"
        Color.Blue -> "파랑"
        Color.Green -> "초록"
      	Color.Yellow -> "노랑"
    }

 

fun getColor(color: Color) =
    when(color) {
    	Color.RED, Color.ORANGE -> "warm"
        Color.GREEN -> "neutral"
        Color.BLUE, Color.INDIGO -> "cold"
      	else -> "잘 모르겠음"
    }

 

 when에 setOf를 사용할 수 있다.

fun mix(c1: Color, c2: Color) =
	when(setOf(c1, c2)) {
    	setOf(RED, YELLOW) -> ORANGE
        setOf(YELLOW, BLUE) -> GREEN
        setOf(BLUE, VIOLET) -> INDIGO
        else -> throw Exception("Dirty Color")
    }

 

 


[ 스마트 캐스트 : 타입 검사와 타입 캐스트 조합 ]

 

fun smartCast(e : Any){
    when (e){
        is Int -> println(e*2) //변수 e가 Int이면 Int로 스마트 캐스트 후 e*2 처리
        is String -> println(e.length) //변수 e가 String이면 String으로 스마트 캐스트 후 e.length 처리
        is IntArray -> println(e.sum()) //변수 e가 IntArray이면 IntArray로 스마트 캐스트 후 e.sum() 처리
        else -> return
}

[ 리팩토링 if => when ]

 

// if
fun eval(e: Expr): Int =
    if(e is Num){
    	e.value
    }
    else if(e is Sum) {
    	eval(e.left) + eval(e.right)
    }
    else {
    	throw IllegalArgumentException("Unknown expression")
    }

 

fun eval(e: Expr): Int = 
    when(e) {
	   is Num -> e.value
 	   is Sum -> eval(e.left) + eval(e.right)
 	   else -> throw IllegalArgumentException("UnKnown expression");
    }

 

728x90