I would like to define a class such as `ScreenStat...
# getting-started
d
I would like to define a class such as
ScreenState
and a function like
emptyScreen()
Copy code
data class AppState (
    val masterState : ScreenState<MasterData> = ScreenState<MasterData>(),
    val detailState : ScreenState<DetailData> = emptyScreen(),
)

data class MasterData (
    val countriesList : List<CountriesListItem> = emptyList(),
    ...
)
data class DetailData (
    val countryInfo : CountryInfo = CountryInfo(),
    ...
)
I was trying to follow the Kotlin definitions of
List
and
emptyList()
but I got stuck it should be something similar to this?
Copy code
public interface ScreenState<screenData T> {
    val isLoading: Boolean = false,
    val screenData: T? = null,
}

public fun <T> emptyScreen(): ScreenState <T> = EmptyScreen

internal object EmptyScreen : ScreenState <Nothing> {
}
y
You're almost there. First generics are defined just as <T> so no need for that "screenData", second you need
out
variance on T so that the
Nothing
thing actually works. Your code should end up being this:
Copy code
public interface ScreenState<out T> {
    val isLoading: Boolean = false,
    val screenData: T? = null,
}
public fun <T> emptyScreen(): ScreenState <T> = EmptyScreen
internal object EmptyScreen : ScreenState <Nothing> {
}
d
@Youssef Shoaib [MOD] thanks so much! however I found that it’s not possible to initialize properties in an interface it looks like with abstract classes is instead possible:
Copy code
abstract class ScreenState<T>(
    val isLoading: Boolean = false,
    val screenData: T? = null,
)

fun <T> emptyScreen(): ScreenState<T> {
    return object : ScreenState<T>() {}
}
y
Well you can do this instead:
Copy code
public interface ScreenState<out T> {
    val isLoading: Boolean get() = false,
    val screenData: T? get() = null,
}
public fun <T> emptyScreen(): ScreenState <T> = EmptyScreen
internal object EmptyScreen : ScreenState <Nothing> {
}
It's basically just default getters which can then be overridden depending on what the subclass wants
d
great! thank you!
👍 1