https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

03/21/2021, 1:42 PM
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

Youssef Shoaib [MOD]

03/21/2021, 3:00 PM
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

Daniele B

03/21/2021, 3:10 PM
@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

Youssef Shoaib [MOD]

03/21/2021, 3:18 PM
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

Daniele B

03/21/2021, 3:58 PM
great! thank you!
👍 1
2 Views