Kotlin Sealed Classes

Kotlin provides a new type of class that is not present in the Java language. It is known as sealed classes. 

In Android Development with Kotlin, a selected class is defined as a set of subclasses. it is known in advance that a type will conform to subclass types. 

Let’s discuss an example of a sealed class.

Syntex: Sealed class of kotlin

Sealed class DemoText

A class can be sealed by using the sealed keyword.

Example: sealed class

//sealed class DemoText

 fun main(args: Array)

 {

var d = Demo() //compiler error

 }

//demo class created 

sealed class Demo {

    class A:Demo(){

        fun display(){

            println("Subclass A of Sealed class ")        }

    }

    class B:Demo(){

        fun display(){

            println("Subclass B of sealed class")

        }

    }

}

 

fun main(args: Array<String>){

//create object demo

    val obj =Demo.B()

    obj.display()

    val obj1=Demo.A()

    obj1.display()

}

Output

Subclass B of a Sealed class

Subclass A of a Sealed class

Example: sealed class another example

fun main(args: Array<String>) {

val e = A.E("Anupam")

println(e) //prints E(name=Anupam)

var d = A.D

d.name() //prints Object D

}

sealed class A{

class B : A()

class C : A()

object D : A()

{

fun name()

{

println("Object D")}}

data class E(var name: String) : A()}

Output

E(name=Anupam)

Object D

Happy coding!


365Bloggy May 13, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive