CUSTOMISED
Expert-led training for your team
Dismiss
How to Use Sealed Classes in Kotlin

6 April 2023

How to Use Sealed Classes in Kotlin

This article is brought to you by JBI Training, the UK's leading technology training provider.   Learn more about JBI's Tech training courses including a range of Kotlin training courses. Kotlin Best Practices & Kotlin Beyond the Basics

Sealed classes are a powerful feature of the Kotlin programming language that can help you define a closed hierarchy of classes. This can be useful in many situations where you need to represent a fixed set of types. In this guide, we'll explain what sealed classes are and how you can use them in your Kotlin projects.

What is a Sealed Class?

A sealed class is a class that can only be subclassed within the same file in which it is declared. This means that you can define a set of classes that are related to each other, but prevent other classes from extending them. Sealed classes are often used to represent a closed set of types, such as the different states of a state machine or the possible responses from a network API.

A sealed class is declared using the sealed keyword, followed by the class name:


 
kotlin

 
sealed class MySealedClass { // Subclasses go here }

Like any other class, a sealed class can have properties, methods, and constructors. However, the constructors of a sealed class must be private:


 
kotlin

 
sealed class MySealedClass(private val value: String) { // Subclasses go here }

Creating Subclasses of a Sealed Class

To create a subclass of a sealed class, you must declare it within the same file as the sealed class and use the sealed keyword followed by the class name. Each subclass can have its own properties, methods, and constructors:


 
kotlin

 
sealed class MySealedClass { class Subclass1(val property1: String) : MySealedClass() class Subclass2(val property2: Int) : MySealedClass() // More subclasses go here }

Note that each subclass must extend the sealed class using the : operator.

Using Sealed Classes in When Expressions

One of the main benefits of sealed classes is that they can be used in when expressions. A when expression is similar to a switch statement in other languages, but it allows you to match against any object, not just primitives. Here's an example of using a sealed class in a when expression:


 
kotlin

 
fun processSealedClass(sealedClass: MySealedClass) { when (sealedClass) { is MySealedClass.Subclass1 -> { // Handle Subclass1 } is MySealedClass.Subclass2 -> { // Handle Subclass2 } // Handle more subclasses here } }

In this example, the when expression matches against the type of the sealed class and executes the appropriate branch based on the type of the object.

Use Cases for Sealed Classes

Sealed classes can be useful in many different scenarios. Here are a few examples:

  • State machines: If you have a state machine with a fixed set of states, you can represent each state as a subclass of a sealed class.
  • Network APIs: If you have an API with a fixed set of responses, you can represent each response as a subclass of a sealed class.
  • Errors: If you have a set of error conditions that your application can encounter, you can represent each error as a subclass of a sealed class.

Conclusion

Sealed classes are a powerful feature of the Kotlin programming language that can help you define a closed hierarchy of classes. By using sealed classes, you can ensure that your code is more type-safe and less error-prone. If you're working on a Kotlin project and need to represent a fixed set of types, consider using sealed classes.

Here are some relevant tech training courses from JBI Training:

  •  Kotlin: Develop Android Apps or Java Backend applications with Kotlin - Reach A Growing And Powerful Mobile Web Audience
  • Kotlin Best Practices: Gain highly effective skills for developing in Kotlin for Android, and Java Backends
  • Kotlin Beyond the Basics: Develop Android Apps or Java Backend applications with Kotlin - Reach A Growing And Powerful Mobile Web Audience 

Here are some official documentation and links for Kotlin:

  1. Kotlin Official Website: https://kotlinlang.org/ - This is the official website of Kotlin where you can find everything related to Kotlin including documentation, tutorials, news, and community resources.

  2. Kotlin Documentation: https://kotlinlang.org/docs/home.html - This is the official documentation of Kotlin which includes a comprehensive guide, tutorials, and references for Kotlin.

  3. Kotlin Programming Guide: https://kotlinlang.org/docs/home.html - This is a detailed guide to Kotlin programming that covers the basics of the language and advanced topics like coroutines, functional programming, and more.

  4. Kotlin Standard Library: https://kotlinlang.org/api/latest/jvm/stdlib/ - This is the official Kotlin Standard Library documentation which includes a list of classes and functions that are available in Kotlin out-of-the-box.

  5. Kotlin Style Guide: https://kotlinlang.org/docs/reference/coding-conventions.html - This is the official Kotlin Style Guide that provides a set of rules and conventions for writing Kotlin code.

  6. Kotlin Coroutines: https://kotlinlang.org/docs/coroutines-overview.html - This is the official Kotlin documentation for coroutines which is a lightweight concurrency framework for Kotlin.

  7. Kotlin Playground: https://play.kotlinlang.org/ - This is an online Kotlin playground where you can write, run, and share Kotlin code snippets.

  8. Kotlin Blog: https://blog.jetbrains.com/kotlin/ - This is the official Kotlin Blog where you can find news, updates, and articles related to Kotlin.

I hope you find these resources helpful in your Kotlin learning journey!

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2024 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course