Kotlin Sealed Class of same Classes

Viewed 329

A KorGE Game Library example game (CounterStrike) has the following construct:

sealed class SideEffect{
    class Hit() : SideEffect()
    class TerroristShot(val terrorist: Terrorist) : SideEffect()
    class KillTerrorist(val terrorist: Terrorist) : SideEffect()
    class ShowTerrorist(val terrorist: Terrorist) : SideEffect()
    class HideTerrorist(val terrorist: Terrorist) : SideEffect()
    class CounterTerroristWin : SideEffect()
    class TerroristsWin : SideEffect()   
}

and I am struggling to understand what the resulting (overall) Object actually is. Does resulting Object actually take up the space of SEVEN SideEffect classes, or ONE? (Or is this a trick question if the classes would all be identical except the name)?

2 Answers

No it just has one possibility.

This concept is more commonly known as an algebraic data type and is used to define a finite set of possibilities that a class can have.

In this case a side effect can therefore have one of the classes that are embedded in the sealed class.

The main advantage of this is that we can do something like this:

fun determineSideEffect(effect: SideEffect) = when(effect){
    is Hit -> do something when hit
    is TerroristShot -> do something when terrorist is shot
    is KillTerrorist -> do something when terrorist is killed
    is ShowTerrorist -> do something when terrorist is shown
    is HideTerrorist -> do something when terrorist is hidden
    is CounterTerroristWin -> do something when counter terrorist wins
    is TerroristsWin ->  do something when a terrorist wins
}

Notice that we don't have an else clause. Normally in a when condition we would need this, however since this is an algebraic data type and the types are known we don't need to specify it.

One way to think about it is as if you don't use sealed at all. You'll have an abstract class SideEffect, a class Hit, a class TerroristShot etc. (because sealed implies abstract).

The only difference with sealed is that the direct subclasses you've listed (Hit, etc.) are the only direct subclasses that SideEffect can ever have. You cannot add more direct subclasses anywhere else in the code.

Therefor you know that any value of type SideEffect must be an instance of one of those 7 subclasses. The SideEffect class itself is abstract, so it can never be instantiated directly.

In terms of to storage sealed class is no different from abstract class and its subclasses are no different than regular classes.

Related