Skip to content

Suggesting all possible options of state using sealed class

Devrath edited this page Aug 9, 2022 · 2 revisions

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 }

}

Animal.kt: -> Class containing all states

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()
Clone this wiki locally