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

Josh Eldridge

01/28/2023, 8:43 PM
Question regarding generics/typing, how would I guarantee the properties parameters I pass into
ScreenInitSettings
are of type
LoginScreenState
which extends
ScreenState
? Posting extra context in the thread:
Copy code
fun Navigation.initLoginScreen(params: LoginScreenParams?) = ScreenInitSettings(
  title = "Login Screen",
  initState = { LoginScreenState(isLoading = true) },
  callOnInit = {
    // update state, after retrieving data from the repository
    stateManager.updateScreen<LoginScreenState> {
      it.copy(
        isLoading = false,
      )
    }
  },
  reinitOnEachNavigation = false,
  callOnInitAlsoAfterBackground = false
)
Copy code
class ScreenInitSettings (
  val title : String,
  val initState : (ScreenIdentifier) -> ScreenState,
  val callOnInit : suspend (StateManager) -> Unit,
  val reinitOnEachNavigation : Boolean = false,
  val callOnInitAlsoAfterBackground : Boolean = false,
)
Copy code
interface ScreenState

data class LoginScreenState (
  val isLoading: Boolean = false,
  val serverName: String = "",
  val serverList: List<String> = emptyList()
): ScreenState
I ran into this issue because I had accidentally passed in a different screen state type of
HomeFeedState
into
initState
and it resulted in a runtime error instead of compile time. If I change
ScreenInitSettings
to use a generic type with an upper bound:
Copy code
class ScreenInitSettings<T: ScreenState> (
  val title : String,
  val initState : (ScreenIdentifier) -> T,
It works, but Android studio tells to remove the explicit type, but if I accidentally use the wrong type it properly corrects me and no longer wants to remove it. I guess my overall question is am I doing it right or is there a better way to do it so Android Studio doesn't recommend remove the type annotation?
g

Gleb Minaev

01/28/2023, 10:51 PM
AS (as well as IDEA) suggests to remove explicit
<LoginScreenState>
only because it can infer it from input arguments. So usually it is sensible to remove it. But if you are afraid to mix up the type you want to use then it is sensible to mark the function return type. Or you can ignore the suggestion to remove the explicit type usage. And even add proper
Suppress
annotation (via shortcut -- Alt+Enter, then "suppress ...").
👍 1
j

Josh Eldridge

01/28/2023, 11:00 PM
Thanks!
5 Views