Open2

kotlinに入門してみる

darmaT0o0darmaT0o0

データクラスについて

https://kotlinlang.org/docs/data-classes.html

data class User(
    val name:String,
    val age:Int
)

Sealed classes and interface

https://kotlinlang.org/docs/sealed-classes.html

  • 制限してクラスを継承したい
  • タイプセーフな設計が必要な時
// Uiの状態
sealed class UiState{
    data object Loading :UiState()
    data class Success(val data: String? = null): UiState()
    data class Error(val error: String?= null): UiState()
}
// ネットワークの状態
sealed interface Error
sealed interface NetworkError: Error
sealed interface DatabaseError: Error
sealed class NetworkResponseState<T>(data: T? = null) : NetworkError {
    class Loading<T> : NetworkResponseState<T>()
    data class Success<T>(val data: T) : NetworkResponseState<T>(data)
    data class Error<T>(val error: String? = null) : NetworkResponseState<T>()
}
// 画面遷移
sealed interface Route

sealed class ActivityRoute(val route:String) : Route {
    data object Home: ActivityRoute(route = "home")
    data object Work:ActivityRoute(route = "work")
}

sealed interface GlanceRoute : Route {
    companion object {
        const val KEY_DESTINATION = "destination"
    }

    data class Home(val route: String = "home") : GlanceRoute
    data class Work(val route: String = "work") : GlanceRoute
}