Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Hello ninjas, Welcome back. Nowadays, people rarely have not heard about “Kotlin”. Kotlin is a programming language used by many android developers.
This article will discuss sealed class in kotlin and how to use them. We will also look into why to use sealed class in kotlin instead of abstract or enum classes.
About Kotlin
Kotlin is very similar to the Java programming language. Only Kotlin is more concise than Java. For example, semicolons do not need to end a statement in Kotlin. It is an open-source programming language developed by JetBrains.
Kotlin is widely used these days because it:
Provides safety features.
Preserves the object-oriented nature of Java.
Suitable for multi-threaded apps.
Provides an extensive number of features.
Consists of 6 different types of classes.
Supports functional programming.
After Google declared Kotlin to be the default programming language for android development, it has become the most demanded language for android development. A lot of IT companies require Kotlin programmers for jobs. It is easy to learn, especially if you are familiar with Java.
Classes in Kotlin
Classes in kotlin define the format for a kotlin object. It works like any other class of object-oriented programming language where classes provide the blueprint for objects.
class <ClassName>
{
< property> <member function>
}
Example
Let’s take the example of cars. A car is the kotlin object. It has wheels, tires, mirrors, etc., which are the vehicle's state. The behavior of the car is its mobility. All cars have the same state and behavior thus, we can create a class that contains all these details about an object. Thus, classes in kotlin are a blueprint of Kotlin objects containing their state and behavior. There are several types of classes like enum, abstract, and sealed class in kotlin.
We will learn about sealed class in kotlin in the next section.
Sealed Class in Kotlin
When we create subclasses in Kotlin with when and else branches, the compiler does not give the appropriate answer. The compiler does not detect the subclasses as the other branch exists. Thus all the conditions in when would not be executed.
Example
The code without sealed class is implemented below as an example with Output.
Implementation
class Arithmetics
class Const(Val value: Int) : Arithmetics
class Sum(Val left: Arithmetics, Val right: Arithmetics) : Arithmetics
fun evaluate(e: Arithmetics): Int =
when (x)
{
is Const -> x.value
is Sum -> evaluate(x.right) + evaluate(x.left)
else ->
throw Exception("Unknown expression")
}
Output
Sealed class in kotlin resolves this problem. Let us see how it solves this in the next section.
How to Use Sealed Class in Kotlin
Sealed class in Kotlin helps to represent the hierarchy of classes. We can define subclasses under the scope of the parent class or function.
Syntax
Sealed class <classname>
{
Class <classname>:<sealed classname>()
Class <classname>:<sealed classname>()
}
A subclass under sealed classes in Kotlin can have multiple parameters and values. These subclasses can be of any type, a data class, object, sealed class in kotlin, or another class. Each subclass extends to the parent class, but the parameters are different. Sealed class in kotlin are restricted so that you can use the class extension only in the existing file. You can not extend a class to a sealed class in kotlin in another file.
Example
We have taken an example below to print the results in a subclass under a sealed class in kotlin.
Implementation
sealed class Print {
class One: Print()
{
fun display() {
println("This is the subclass One under sealed class Print ")
}
}
class Two:Demo(){
fun display(){
println("This is the subclass Two under sealed class Print")
}
}
}
fun main(args: Array<String>){
val object1 =Print.One()
object1.display()
val object2=Print.Two()
object2.display()
}
Output
The above example shows that subclasses one and two are detected by the compiler, and the code is executed properly. As discussed above, this sealed class in kotlin in the file “Print” can not be used in any other file.
Sealed Class in Kotlin with When Expression
The “when” expression in kotlin replaces if, else-if, nested if, and switch in Java. It also has an “else” branch which has no use under a sealed class in kotlin.
Example
In the below given example, we will print output using the “when” expression by calling out the subclasses under the “colour” sealed class in kotlin.
Implementation
sealed class Colour(Val a : String)
{
// Subclass under the sealed class
class Yellow : Colour("Yellow")
class Blue : Colour("Blue")
}
// Subclass outside the sealed class
class Red: Colour("Red")
fun display(colour: colour)
{
// Using sealed classes with when
when(colour)
{
is Colour.Yellow -> println("${Colour.a} symbolises happiness")
is Colour.Blue -> println("${Colour.a} symbolises freedom")
is Red -> println("${Colour.a} symbolises love")
}
}
fun main()
{
val object1= Colour.Yellow()
val object2 = Colour.Blue()
val object3 = Red()
display(object1)
display(object2)
display(object3)
}
Output
We can see in the above example that the “when” expression works for subclasses under sealed class in kotlin and also for subclasses outside sealed classes in kotlin. If we notice, we will also see that the “else” branch is unnecessary, as there are no conditions under a sealed class in kotlin that are not caught or detected by the compiler.
Why Sealed Class Over Enum Class
Developers prefer sealed class in kotlin over enum classes because
Subclasses can be defined outside the sealed class in kotlin, whereas in the enum class, subclasses are only defined within the enum class.
Unlike enum classes, different states of subclasses can be contained in sealed class in kotlin. In enum classes, storing the different states of other subclasses is difficult.
Unlimited subclasses can exist under sealed class in kotlin, whereas in enum classes, only a few subclasses can be executed properly.
You can add custom constructors in a sealed class in kotlin, unlike in an enum class, where you can not define various functions under the enum class.
Kotlin provides a lot more features than Java. It also makes some functions and statements easier to write, for example, the removal of semicolons. Kotlin code takes more time to run, but that is because of the large number of inbuilt functions and features.
What are enum classes in Kotlin?
The Enum class in Kotlin represents a group of constants. Only a few subclasses can be stored under an enum class.
What is an abstract method?
An abstract method does not have a body, i.e. it can’t be defined inside an abstract class. It is defined inside the derived class of the same abstract class.
What is the visibility scope of a constructor?
By default, all constructors are visible as public. But we can also change the visibility of constructors by adding appropriate access modifiers.
What is the difference between private and protected access modifiers?
The protected access modifiers have the same functionality as the private access modifier. The only difference is that variables and functions declared protected also viewable in subclasses.
Conclusion
This article discussed what is sealed class in Kotlin. We also learned why we need to use sealed class in kotlin and how to create them. We discussed how to use a sealed class in kotlin with the “when” expression and why we use a sealed class in kotlin over an enum class. To learn more about Kotlin, refer to: