Daniel
01/03/2020, 7:03 PMsealed class Level {
abstract val exercise: Exercise
abstract val finished: Boolean
data class PresetLevel(
override val exercise: Exercise,
override val finished: Boolean) : Level()
data class GeneratedLevel(
override val exercise: Exercise,
override val finished: Boolean) : Level()
}
Both children are data classes but since there is no "type" data class I can't say level.copy(..)
even though both child classes have a copy methodRan Magen
01/03/2020, 7:06 PMcopy
in the sealed class and have it be final?streetsofboston
01/03/2020, 7:08 PMDaniel
01/03/2020, 7:08 PMcopy(..)
to the sealed class and I get an compile error that it clashes with the copy method generated by data
😕streetsofboston
01/03/2020, 7:10 PMdata interface LevelIfc {
val exercise: Excercise
}
sealed class Level: LevelIfc {
override val exercise: Excercise
abstract val finished: Boolean
...
}
Now Level.copy(…)
would have been generated, but alas data-interface don’t exist…Ran Magen
01/03/2020, 7:13 PMfun Level.mkCopy(): Level {
when(this) {
is PresetLevel -> ..
is GeneratedLevel -> ..
}
}
Ran Magen
01/03/2020, 7:13 PMDaniel
01/03/2020, 7:16 PMLevel
type 😕
override fun finishLevel(level: Level) {
val finishedLevel = level.copy(
finished = true,
// other stuff
)
when(finishedLevel) {
is PresetLevel -> presetLevelDatabase.saveLevel(finishedLevel)
is GeneratedLevel -> generatedLevelDatabase.saveLevel(finishedLevel)
}
}
This can be achieved, but I only could do it when I define my own abstract copy method in the sealed classRan Magen
01/03/2020, 7:20 PMLevel
is a sealed class, so all the concrete types that extend it are in the same file..Daniel
01/03/2020, 7:21 PMwhen
Then I have the type PresetLevel
instead of just Level
then the copy method of the data class would be availableRan Magen
01/03/2020, 7:26 PMRan Magen
01/03/2020, 7:28 PMClass LevelService(db: DbService) {
fun finishLevel(level: Level) {
when (level) {
is PresetLevel -> db.savePresetLevel(level.copy(finished = true))
is .. -> db.saveWhatever(level.copy(finished = true))
}
}
}
Ran Magen
01/03/2020, 7:28 PMDaniel
01/03/2020, 7:29 PMoverride fun finishLevel(level: Level)
method is in an repository and is responsible to bring the level in the finished state.
The Level itself does not know anything, only its properties.
The thing is: like you posted, I want to avoid the repetitionDaniel
01/03/2020, 7:30 PMcopy
method on the sealed class seems to be the only way - since the sealed class can't know that its subtypes are data classes 😕Ran Magen
01/03/2020, 7:36 PMLevel
are created.Daniel
01/03/2020, 7:38 PMcopy
methods in the end! Thank you for your replies!