룬아님의 취중코딩

(Kotlin) Singleton, enum, Sealed Class 본문

개발/Kotlin

(Kotlin) Singleton, enum, Sealed Class

룬아님 2019. 11. 29. 18:31

1. Singleton

object GoldColor : FishColor {
   override val color = "gold"
}

 

2. enum

enum class Direction(val degrees: Int) {
    NORTH(0), SOUTH(180), EAST(90), WEST(270)
}

fun main() {
    println(Direction.EAST.name)
    println(Direction.EAST.ordinal)
    println(Direction.EAST.degrees)
}
⇒ EAST
2
90

 

3. Sealed

sealed class Seal
class SeaLion : Seal()
class Walrus : Seal()

fun matchSeal(seal: Seal): String {
   return when(seal) {
       is Walrus -> "walrus"
       is SeaLion -> "sea lion"
   }
}

Sealed 클래스는 보기에는 inner class랑 비슷하지만 when 표현식을 쉽게 사용할 수 있는 이점이 있다.
Google blueprint에서는 Sealed 클래스를

sealed class Result<out R> {

    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
    object Loading : Result<Nothing>()

    override fun toString(): String {
        return when (this) {
            is Success<*> -> "Success[data=$data]"
            is Error -> "Error[exception=$exception]"
            Loading -> "Loading"
        }
    }
}

 

suspend fun searchRepositories(searchKeyWord: String): Result<RepositoriesResponse> =
    withContext(ioDispatcher) {
        return@withContext try {
            Success(gitHubAPI.searchRepositories(searchKeyWord))
        } catch (e: Exception) {
            Error(e)
        }
    }

이렇게 비동기 작업의 Return으로 사용하도록 구현하였다.

위 코드를 통해 간단하게 Sealed 클래스를 이용하여 when 표현식으로 어떻게 활용하는지를 알 수 있다.

반응형
Comments