Search code examples
kotlinsealed-class

Practical example of sealed classes in Android Development


I'm newbie of Kotlin. I'm learning sealed classes and I don't understand how could I use it in Android development. Can you give me an example?


Solution

  • It's useful when you want to define a closed list of subclasses.

    You can use possibility for data classes to extend sealed classes . Example:

     fun eval(expr: Expr): Double = when(expr) {
       is Const -> expr.number
       is Sum -> eval(expr.e1) + eval(expr.e2)
       NotANumber -> Double.NaN
      // the `else` clause is not required because we've covered all the cases
     }
    

    Declaration:

    sealed class Expr
    data class Const(val number: Double) : Expr()
    data class Sum(val e1: Expr, val e2: Expr) : Expr()
    object NotANumber : Expr()