Kotlin Sealed Classes
In Kotlin, sealed classes are used to represent restricted class hierarchies.
A sealed class can only be subclassed from inside the same package where the sealed class is declared.
For example, consider the following sealed class.
sealed class Person(val name: String)
This sealed class can only be subclassed within the package. Let us create two more classes with Person class as parent.
sealed class Person(val name: String)
class Student(val studentName: String) : Person(studentName)
class Teacher(val teacherName: String, val subject: String) : Person(teacherName)
Now, let us write a program, where in the main function, we create objects of type Student, and Teacher, and use them to create a greeting message.
Kotlin Program
sealed class Person(val name: String)
class Student(val studentName: String) : Person(studentName)
class Teacher(val teacherName: String, val subject: String) : Person(teacherName)
fun greetPerson(person: Person): String {
when (person) {
is Student -> return "Hello ${person.name}!"
is Teacher -> return "${person.name} teaches ${person.subject}."
}
}
fun main() {
val student1 = Student("Ram")
val teacher1 = Teacher("Krishna", "Mathematics")
println(greetPerson(student1))
println(greetPerson(teacher1))
}
Output
Hello Ram!
Krishna teaches Mathematics.