Skip to content

About sealed class in android

Devrath edited this page Aug 9, 2022 · 15 revisions

Sealed classes are abstract classes

There are only abstract methods defined and concrete implementations are defined.

sealed class Animal {
    object Cat : Animal() // We can define a Object classes like this 
    data class Dog(val name: String) : Animal() // We can define data classes like this
}

All the members of the sealed class must be defined in the same file

  • Here you can observe that we are inheriting Animal for Camel and Monkey but it's defined in the same file. If we try to inherit in another file, it will not work.
  • What the sealed modifier does is, it is impossible to define another subclass outside the file.
  • Because of this, we know the sub-classes of a class by just analyzing a single file.

Animal.kt

package com.demo.subclasses

sealed class Animal {
    object Cat : Animal() // We can define a Object classes like this
    data class Dog(val name: String) : Animal() // We can define data classes like this
}
object Camel : Animal()
object Monkey : Animal()

Suggesting all possible options

  • If we use when option, the compiler will recommend all the options(subclasses) of the sealed class state.
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val catData = getCats()

        when(catData){
            is Camel -> { /* Some logic */ }
            is Animal.Cat -> { /* Some logic */ }
            is Animal.Dog -> { /* Some logic */ }
            is Monkey -> { /* Some logic */ }
        }

    }

    fun getCats() : Animal {  return Animal.Cat }

}

A bit of understanding on how classes are different in kotlin compared to java

  • In kotlin classes are final by default meaning they cannot be inherited by just extending.
  • We need to explicitly make them open to be inherited.
  • Sealed classes fit between final and open. This Final <-------> Sealed classes <-------> Open
  • So sealed classes help in taking advantage of inheritance but in a limited format.
  • This will ensure we don't end up with a massive long inheritance tree and not knowing easily where its inherited by whom but here all the children are in same class.
Clone this wiki locally