You are here
Home > Kotlin

Kotlin: Class delegation & Sealed Classes

Class delegation and Sealed Classes

Kotlin: Class delegation & Sealed Classes

In this post we will discuss class delegation and sealed classes in kotlin.

Class delegation

  • A delegate is a reference type variable that holds the reference to a class. The reference can be changed at runtime.
  • A delegate acts as the tunnel between two kinds of objects- moving from one side to another side.
  • The by keyword is used to generate all function for object after the by

Example

interface Base {
fun display()
}
class BaseImpl(val x: Int) : Base {
override fun display() { print(x) }
}
class Derived(b: Base) : Base by b
fun main(args: Array<String>) {
val b = BaseImpl(10)
Derived(b).display() // prints 10

val d= Derived(BaseImpl(2));
d.display();
}

output:

Explanation:

Interface Base is implemented by class BaseImpl and it override the display() function. Class Derived also extends the interface b will be stored internally in objects of Derived and compiler generate all the functions of base that forward to b.

 

Sealed Classes

  • A sealed class in kotlin is an abstract class, which can be extended by subclasses defined as nested classes within the sealed class itself.
  • Just like enum it contains a fixed set of possible choices.
  • Class can be declared as sealed by putting the keyword sealed before class definition.
  • A sealed class cannot be used as a base class. Sealed classes prevent derivation. Because they can never be base class.
  • A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself.
  • It is same as enum, unlike enum each option is represented by one instance, the derived class of a sealed class can have many instances.
  • In Kotlin we can also use sealed classes combined with when Allowing compiler to verify all branch statements, making the statement else unnecessary.

Example:

sealed class Action{
class Click:Action()
class Select:Action()
}
fun main(args:Array<String>)
{
val action:Action=Action.Click()
val o=when(action){
is Action.Click->”Click”
is Action.Select->”select”
}
println(o);
}

 output:

Explanation:

we create a sealed class Action within this class we create two inner class Click and Select that extend the sealed class. In main function, we create an object of Action class with click action. We use when expression to match the case.

Keep Visiting TechwithR.com for more upcoming top technical articles and also see my new blog Mag4info. and for kotlin tutorial also see my blog kotlin category.

For online shopping visit BestBuy101.com
You can also by SQL 70-761 book write by me from Amazon.
You can also by Kotlin Book write by me from Amazon.

 

Leave a Reply

Top