본문 바로가기
카테고리 없음

[Kotlin] Sealed Class, Interface 사용법 (2) - Sealed Class, Interface vs Enum

by 노력남자 2023. 6. 21.
반응형

이번 포스팅에선 Sealed Class, Interface를 어떻게 사용해야 하는지를 찾아보다보니 Enum과 비교하는 글이 좀 있길래 정리해보려고 한다.

 

Enum에 대해선 예전 포스팅을 참고바란다.

 

Sealed Class, Interface vs Enum

 

어떤 글을보니 sealed class, interface는 enum 확장된 버전이라고 하는데 나는 이거에 동감하지 않는다.

 

각각 용도가 분명히 있다.

 

sealed class, interface와 enum을 비교하는 게 맞는 건가 싶지만 왜 비교를 하는지 확인해보자.

 

차이점

 

이걸 차이점이라고 하는 게 맞는지 잘 모르겠다.

 

enum

 

entry들은 동일한 프로퍼티를 가질 수 밖에 없는 구조다.

 

enum class UserType(
    code: String
) {
    ADMIN("A"),
    NORMAL("N")
}

 

sealed class, interface

 

상속, 구현한 클래스들은 프로퍼티를 다르게 가질 수 있다.

 

sealed interface UserType {
    class Admin(val code: String, val auths: List<String>) : UserType
    class Normal(val code: String): UserType
}

 

공통점

 

enum은 컴파일 시점에 entry를 모두 알 수 있다.

 

sealed class, interface도 컴파일 시점에 자신을 상속, 구현한 object를 모두 알 수 있다.

 

그래서 아래와 같이 when에 else를 안 쓸 수 있다는 공통점이 있다.

 

enum

 

fun getCommission(userType: UserType) =
    when (userType) {
        UserType.ADMIN -> 50_000
        UserType.NORMAL -> 0
    }

 

sealed class, interface

 

fun getCommission(userType: UserType) =
    when (userType) {
        is UserType.Admin -> 50_000
        is UserType.Normal -> 0
    }

 

반응형

댓글