How to Write Sealed Class In Kotlin?

10 minutes read

A sealed class in Kotlin is a class that can only have a fixed set of subclasses. To write a sealed class in Kotlin, you first declare the sealed modifier before the class keyword. This ensures that all subclasses of the sealed class are defined within the same file.


Once you have defined the sealed class, you can then create your subclasses using the sealed class name followed by the class keyword. These subclasses must be defined within the same file as the sealed class to be valid.


Sealed classes are useful for representing restricted hierarchies where all possible subclasses are known ahead of time. They can help make your code more robust and predictable by enforcing a limited set of subclasses.

Best Kotlin Books to Read in November 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.9 out of 5

Kotlin Cookbook: A Problem-Focused Approach

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin in Action

Rating is 4.7 out of 5

Kotlin in Action

5
Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

Rating is 4.6 out of 5

Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

6
Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

Rating is 4.5 out of 5

Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

7
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.4 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

8
Java to Kotlin

Rating is 4.2 out of 5

Java to Kotlin

9
Kotlin Essentials (Kotlin for Developers)

Rating is 4.1 out of 5

Kotlin Essentials (Kotlin for Developers)


How to define sealed classes with generic type parameters in Kotlin?

Sealed classes with generic type parameters can be defined in Kotlin using the following syntax:

1
2
3
4
sealed class Result<out T> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val error: String) : Result<Nothing>()
}


In this example, Result is a sealed class with a generic type parameter T. It has two subclasses: Success and Error. Success is a data class that contains a generic type T as its property, while Error is a data class that does not have a generic type parameter. By using sealed classes with generic type parameters, you can create a data structure that represents a result with either a success value of type T or an error message.


What is the effect of sealed classes on code organization and readability in Kotlin?

Sealed classes in Kotlin can have a positive effect on code organization and readability.

  1. Code organization: Sealed classes can help organize related classes or hierarchies within a single file or package. This can make it easier for developers to understand the relationships between different classes and to locate related code. Sealed classes also enforce a restricted hierarchy, ensuring that all subclasses are defined within the same file or package, which can help prevent the scattering of related code across multiple files or packages.
  2. Readability: Sealed classes can improve code readability by providing a clear and concise way to define a closed set of subclasses. When a developer sees a sealed class, they know that there are a finite number of subclasses that extend it, making it easier to reason about the code and understand its behavior. Sealed classes also encourage the use of exhaustive when statements, where all possible cases are handled, contributing to clearer and more robust code.


In summary, sealed classes can enhance code organization and readability by grouping related classes together and providing a clear and concise way to define a restricted hierarchy of subclasses.


How to compare sealed classes in Kotlin?

In Kotlin, sealed classes are used to represent restricted class hierarchies. Unlike regular classes, which can be instantiated freely, sealed classes have a restricted set of subclasses that must be declared within the same file.


To compare sealed classes in Kotlin, you can use a when expression or pattern matching to compare instances of sealed classes. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
sealed class Result
class Success(val message: String) : Result()
class Error(val message: String) : Result()

fun main() {
    val result1: Result = Success("Data loaded successfully")
    val result2: Result = Error("Error loading data")

    when {
        result1 is Success && result2 is Success -> {
            println("Both results are successes.")
        }
        result1 is Error && result2 is Error -> {
            println("Both results are errors.")
        }
        else -> {
            println("Results are different types.")
        }
    }
}


In the example above, we have a sealed class Result with two subclasses Success and Error. We compare two instances of Result using a when expression to determine if they are of the same type or not. This way, you can compare sealed classes in Kotlin by checking their types and properties.


How to define subclasses for a sealed class in Kotlin?

To define subclasses for a sealed class in Kotlin, you need to create separate classes that extend the sealed class. Sealed classes are used to represent restricted class hierarchies with a limited set of possible subclasses. Here's an example of how you can define subclasses for a sealed class in Kotlin:

1
2
3
4
5
sealed class Shape {
    class Circle(val radius: Double) : Shape()
    class Square(val sideLength: Double) : Shape()
    class Triangle(val base: Double, val height: Double) : Shape()
}


In this example, the Shape sealed class has three subclasses - Circle, Square, and Triangle. Each subclass has its own properties that define the specific shape. You can then create instances of these subclasses and use them accordingly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
fun calculateArea(shape: Shape): Double {
    return when (shape) {
        is Shape.Circle -> Math.PI * shape.radius * shape.radius
        is Shape.Square -> shape.sideLength * shape.sideLength
        is Shape.Triangle -> 0.5 * shape.base * shape.height
    }
}

fun main() {
    val circle = Shape.Circle(5.0)
    val square = Shape.Square(4.0)
    val triangle = Shape.Triangle(3.0, 4.0)

    println("Circle area: ${calculateArea(circle)}")
    println("Square area: ${calculateArea(square)}")
    println("Triangle area: ${calculateArea(triangle)}")
}


In this example, we define a calculateArea function that takes a Shape object as a parameter and calculates the area based on the specific subclass. We then create instances of each shape subclass and use the calculateArea function to calculate their respective areas.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

Sealed classes in Kotlin are used to represent restricted class hierarchies, where a class can have only a limited number of subclasses. They are declared using the sealed modifier before the class declaration.Working with sealed classes involves the following...
In Kotlin, we can allow Result&lt;T&gt; to be a return type by utilizing generics and the sealed keyword.The Result class represents a computation that either succeeded with a value of type T, or failed with an exception. It has two subclasses: Success and Err...
To call a Kotlin function from JavaScript, you can use the Kotlin/JS plugin that allows you to compile Kotlin code to JavaScript. First, define your Kotlin function in a Kotlin file using the external keyword to tell the Kotlin compiler that this function will...
To extend an entity class in Spring Boot with Kotlin, you can create a new Kotlin class that inherits from the entity class you want to extend. By using the open keyword before the entity class, you can allow it to be extended by other classes. Then, in your n...
In Kotlin, you can pass the class type to a function using a combination of the ::class.java syntax and the Class&lt;T&gt; type. Here&#39;s how you can do it:First, define a function that takes the class type as a parameter. For example: fun processClassType(c...
In Kotlin, a nested data class is a class that is declared within another class. To initialize a nested data class, you can follow these steps:Declare the outer class: class OuterClass { // Declare the nested data class within the outer class data...