- Kotlin - Exception Handling
- Kotlin - Destructuring Declarations
- Kotlin - Delegation
- Kotlin - Generics
- Kotlin - Sealed Class
- Kotlin - Data Classes
- Kotlin - Extension
- Kotlin - Visibility Control
- Kotlin - Interface
- Kotlin - Abstract Classes
- Kotlin - Inheritance
- Kotlin - Constructors
- Kotlin - Class and Objects
- Kotlin - Maps
- Kotlin - Sets
- Kotlin - Lists
- Kotlin - Collections
- Kotlin - Break and Continue
- Kotlin - While Loop
- Kotlin - For Loop
- Kotlin - When Expression
- Kotlin - if...Else Expression
- Kotlin - Control Flow
- Kotlin - Functions
- Kotlin - Ranges
- Kotlin - Arrays
- Kotlin - Strings
- Kotlin - Booleans
- Kotlin - Operators
- Kotlin - Data Types
- Kotlin - Variables
- Kotlin - Keywords
- Kotlin - Comments
- Kotlin - Basic Syntax
- Kotlin - Architecture
- Kotlin - Environment Setup
- Kotlin - Overview
- Kotlin - Home
Kotlin Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Kotpn - Sealed Class
In this chapter, we will learn about another class type called “Sealed” class. This type of class is used to represent a restricted class hierarchy. Sealed allows the developers to maintain a data type of a predefined type. To make a sealed class, we need to use the keyword “sealed” as a modifier of that class. A sealed class can have its own subclass but all those subclasses need to be declared inside the same Kotpn file along with the sealed class. In the following example, we will see how to use a sealed class.
sealed class MyExample { class OP1 : MyExample() // MyExmaple class can be of two types only class OP2 : MyExample() } fun main(args: Array<String>) { val obj: MyExample = MyExample.OP2() val output = when (obj) { // defining the object of the class depending on the inuputs is MyExample.OP1 -> "Option One has been chosen" is MyExample.OP2 -> "option Two has been chosen" } println(output) }
In the above example, we have one sealed class named “MyExample”, which can be of two types only - one is “OP1” and another one is “OP2”. In the main class, we are creating an object in our class and assigning its type at runtime. Now, as this “MyExample” class is sealed, we can apply the “when ” clause at runtime to implement the final output.
In sealed class, we need not use any unnecessary “else” statement to complex out the code. The above piece of code will yield the following output in the browser.
option Two has been chosenAdvertisements