Home > database >  How to read sealed class subclass in Kotlin?
How to read sealed class subclass in Kotlin?

Time:04-22

In my Android studio project, I have a construct like following:

@Stable
interface Levels {

    @Immutable
    sealed class LevelData {

        object Empty : LevelData()

        @Immutable
        data class L1(
            val locationData: Locations.LocationData.StageL1
        ) : LevelData()
    }
}

In another class I have val levelData = mutableStateOf<Levels.LevelData>(Levels.LevelData.Empty) variable with Empty as its default. Then the state changes and I would like to access the locationData in levelData like levelData.value.locationData?

Autocomplete in Android Studio does not show me any locationData member access in the drop down?!?

CodePudding user response:

Your levelData variable holds mutable state of super type Levels.LevelData. You need to cast the object to L1 to access locationData

val value = levelData.value
if(value is Levels.LevelData.L1){
    val locationData = value.locationData
    //perform action on locationData
} 
  • Related