Hi,
If I have a sealed class which is implemented by data classes, how can I make a property shared amongst each implementation of the sealed class have a default value?
For example, in a small game, where players have a name and chips, in order to give all players by default 100 chips, I currently have to do something like this (which looks very ugly):
sealed class Player {
abstract val name: String
abstract val chips: Int
companion object {
const val DEFAULT_CHIPS = 100
}
}
data class Human(
override val name: String,
override val chips: Int = DEFAULT_CHIPS,
) : Player()
data class AI(
override val chips: Int = DEFAULT_CHIPS
) : Player() {
override val name = "AI"
}
Ideally, I would want something like this:
sealed class Player(
val name: String,
val chips: Int = 100,
)
data class Human(
override val name: String,
override val chips: Int,
) : Player
data class AI(
override val chips: Int
) : Player {
override val name = "AI"
or even
sealed class Player {
abstract val name: String
protected val chips = 100
}
data class Human(
override val name: String,
override val chips: Int
) : Player()
data class AI(
override val chips: Int
) : Player() {
override val name = "AI"
}
Does anyone have any thoughts on how I could do this? or is this something that Kotlin doesn’t offer (yet)?
Many thanks!