How to create a default value for a sealed class property?

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!

I mean, you have a sealed class not a sealed interface, so you could just provide the implementation rather than overriding it. Another thing i find useful is a null object pattern to provide a valid instance that represents no value but isn’t null (useful in Kotlin Flows etc). Otherwise if you’re after a static value, then the companion object is the way.

sealed class Player {
    abstract val name: String
    val chips: Int = 100

    object NullPlayer : Player() {
        overrride val name: String = "NullPlayer"
        override val chips: Int = 0
    }
}

data class Human(
    override val name: String,
) : Player()

data class AI(
    override val name: String = "AI",
) : Player()

Great thanks!