Skip to main content

Kotlin Sealed Class

Sealed Class are used to implement restricted hierarchical structure. That is useful when we are know about what kind of operation are perform by specified object (inherited class objects). This object is decide what information are getting and which kind of operations will executing.

Sealed class defining rules

sealed class start with sealed keyword followed by class keyword and name of this class.

sealed class Person

Body of this class are not compulsory that can be empty, or defining by programmer.

sealed class Person{
  
  class Employee:Person(){

    //class properties
  }

  class Doctor:Person(){
    //class properties
  }
}

By default constructor of sealed class is private. And that subclass are must be define on a same file. sealed class are abstract itself.

sealed class SetInfo(var info:String=" "){
   class Sub1:SetInfo("Sub1")
   class Sub2:SetInfo("Sub2")
}
fun main(args: Array<String>){
  //access subclass
  val obj1=SetInfo.Sub1()
  println(obj1.info) //Sub1
  val obj2=SetInfo.Sub2()
  println(obj2.info) //Sub2
}

Output

Sub1
Sub2

Scope of Sealed class is exist with on its subclass. and also exist outside fine class but outer class. inner class of outside of class is not capable to access. See this example.

sealed class SetInfo(var info:String=" "){

   class Sub1:SetInfo("Sub1"){
      //okay possible to access nested all inner class   
      class Sub11:SetInfo("Sub11")
   }
   class Sub2:SetInfo("Sub2")
}

//okay possible to access of outside parent class
class Test:SetInfo("Test"){
   
   //not access
   class TestSub1:SetInfo("TestSub1")
}
fun main(args: Array<String>){
 
}

Output

kotlin.kt:14:17: error: cannot access '<init>': it is private in 'SetInfo'
   class TestSub1:SetInfo("TestSub1")
                ^
kotlin.kt:14:17: error: this type is sealed, so it can be inherited by only its own nested classes or objects
   class TestSub1:SetInfo("TestSub1")
                ^

Example of sealed class

sealed class Person

data class Details(var name:String,var address:String):Person()

data class Hobby(var type1:String,var type2:String):Person()

fun showMe(info:Person):String{

  val myInfo=when(info){
    is Details -> "Name: ${info.name}  Address : ${info.address}"
    is Hobby   -> "My Hobby is ${info.type1} and ${info.type2}"
  }
  return myInfo

  
}
fun main(args: Array<String>){
  
  val hobby:String   = showMe(Hobby("Coding","Cricket"))
  val details:String = showMe(Details("Code Gunner","Every Where"))
  println("${details} \n ${hobby}")
}

Output

Name: Code Gunner  Address : Every Where 
 My Hobby is Coding and Circket





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment