Updated April 17, 2023
Introduction to Kotlin Sealed Class
The kotlin sealed class is one of the built-in classes that can be used to restrict the users from inheriting the class. It can be sealed using the sealed keyword. If we used and declared the class with a sealed keyword, then it automatically tells to the compiler that the class is sealed, and therefore it cannot be extended with the other child classes like that; similarly, we can use the sealed keyword in the method so that it cannot be declared as the virtual part in the base class. If suppose the class is derived from the sealed class, it throws an error.
Syntax of Kotlin Sealed Class
The kotlin language has many features for implementing the mobile-based application, like that the sealed class is the name that can be suggested to take only the values from the limited set of values it cannot be inherited.
sealed class name{
class name1:name()
class name2:name()
}
fun main(args:Array<String>){
val c=name.name1()
---some logics depends on the requirement---
}
The above codes are the basic syntax for declaring the sealed class with other child classes. The sealed class cannot be inherited, so that we can call the methods on the main method with the help of its reference.
How does Sealed Class work in Kotlin?
The sealed class of the keyword that can be represented and it can be used to restrict the class and its hierarchy, where an object or value can be of the same type from the limited set of values. All the subclasses and other child classes when is of the sealed class it can be known at the compile time no other subclasses may appear after at the module with the sealed class compilation. The sealed class has some restriction for running the projects in the multiplatform direct sub, and child classes of the sealed classes must reside in the same data source set.
Mainly we cannot create the object of the sealed classes so that the sealed classes cannot be instantiated; also, all the sub and child classes of the sealed classes must be declared within the same file where the sealed class is to be declared on it. And also, the constructor of the sealed class is by default private access modifiers, and we cannot make it as non-private like public, protected etc. We can also evaluate the expression if it’s required by the user end, and probably the eval() method is used to evaluate the coding. If the error is coming, then the compiler is warned without adding the logics in the expression code.
Examples of Kotlin Sealed Class
Given below are the examples of Kotlin Sealed Class:
Example #1
Code:
package one;
sealed class Demo{
class demo1 : Demo()
class demo2 : Demo()
class demo3 : Demo()
}
fun eval(c: Demo) =
when (c) {
is Demo.demo1 -> println("Provide your first input in demo1 Demo")
is Demo.demo2 -> println("Provide your second input in demo2 Demo")
is Demo.demo3 -> println("Provide your third input in demo3 Demo")
}
fun main(arg: Array<String>) {
val out = Demo.demo1()
eval(out)
var a= "Welcome Users its a first example regarding sealed class"
var b = try { a.toInt() } catch (e: NumberFormatException) { "Have a Nice day users" }
println(b)
a = "1234"
b = try { a.toInt() } catch (e: NumberFormatException) { "Thank you users for giving your inputs" }
println(b)
try {
var d = 13 / 0
val f = ""
f.toInt()
} catch (e: ArithmeticException) {
println("Its a error please catch your exception")
} catch (e: Exception) {
println("Exception occurred please find the stacktrace print using e")
} finally {
println("Thank you for spending the time with us")
}
}
Output:
The above example is the sealed class example with performed the exceptions like Arithmetic exception etc.
Example #2
Code:
package one;
sealed class second {
class exam : second() {
fun show()
{
println("Welcome To My Domain its a second example regarding kotlin sealed class")
}
}
class sample : second() {
fun show()
{
println("Its a child sealed class")
}
}
}
fun main(args:Array<String>)
{
val eg = second.sample()
eg.show()
val eg1 = second.exam()
eg1.show()
var firsts = Triple("This is the first input", "This is the second input","This is the third input")
val result1: List<Any> = firsts.toList()
println(result1)
var second = Triple("First input is the string based input", 1.67543 ,
listOf(6789, "We passed the string inputs on the second placeholder", 1234556))
val result2: List<Any> = second.toList()
println(result2)
var third = Triple("This is the fourth input", "This is the fifth input","This is the sixth input")
val result3: List<Any> = third.toList()
println(result3)
println("Thank you users your kotlin Example login codes which based on the sealed class concept and the net output result is : " + result2)
}
Output:
In the second example, we used the collection concept combined with the sealed classes.
Example #3
Code:
package one;
abstract class Employee(empname:String){
abstract var name: String
abstract fun empdetails()
init {
println("Employee name is: $name")
}
fun demo(){
println("Thank you the Employee name is")
}
}
interface Employer {
var vars: String
fun demo1():String
fun details2() {
println("Have a Nice day users")
}
}
class Employee1 : Employer {
override var vars: String = "May"
override fun demo1() = "June"
}
class Employee2(empname:String): Employee(empname) {
override var name: String = "July"
override fun empdetails() {
println("Thank you users your Employee is $name")
}
}
sealed class third {
class demo : third() {
fun show()
{
println("Welcome To My Domain its a third example regarding kotlin sealed class")
}
}
class demo1 : third() {
fun show()
{
println("Its a child sealed class")
}
}
}
fun main(args:Array<String>)
{
val eg = third.demo1()
eg.show()
val eg1 = third.demo()
eg1.show()
val m2 = Employee2("May")
println("Your curent Employee is : ${m2.name}")
m2.empdetails()
val j = Employee1()
println("Your latest Employee is = ${j.vars}")
print("Keep on spent the time with our application: ")
j.details2()
print("Nice day users please try again ")
println(j.demo1())
}
Output:
In the final example, we used to the interface, and the abstract class joined with the sealed classes. Here we stored and retrieved the employee details.
Conclusion
In kotlin, language classes contain default methods, and their attributes are performed in the application implementation. Like that sealed classes are most powerful, and extensions like enum data types and it does not have the object instance for calling their methods on the main method so that we can inherit with the child classes to access it.
Recommended Articles
This is a guide to Kotlin Sealed Class. Here we discuss the introduction, syntax, and working of sealed class in kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –