Kotlin / Data Classes and Sealed Classes

Using Sealed Classes for Data Modeling

In this tutorial, you will learn about sealed classes in Kotlin, which are used to represent restricted class hierarchies. You'll understand how to use them for better type safety…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Teaches how to work with data and sealed classes in Kotlin for better data modeling.

Introduction

In this tutorial, we will explore an important feature of Kotlin programming language - Sealed Classes. Sealed classes are used to represent restricted class hierarchies, allowing a value to have one of the types from a limited set. They are often used for modeling data in a way that provides better type safety.

After completing this tutorial, you will understand:
- What sealed classes are
- How to create and use sealed classes
- How sealed classes can improve type safety and data modeling

Prerequisites:
- Basic knowledge of Kotlin programming language
- Familiarity with object-oriented programming concepts

Step-by-Step Guide

What are Sealed Classes?

In Kotlin, a sealed class is a class that can have a limited number of subclasses. Unlike regular classes, sealed classes allow you to restrict the class hierarchy. This means, you can control what types can be created from a sealed class.

To declare a sealed class, you use the sealed keyword before the class keyword:

sealed class MySealedClass

How to Use Sealed Classes?

To use a sealed class, you define subclasses of it. You can define these subclasses either within the parent class or outside of it.

sealed class MySealedClass {
    class SubClass1 : MySealedClass()
    class SubClass2 : MySealedClass()
}

When you define a variable of the sealed class type, you can assign it instances of its subclasses:

val myVar: MySealedClass = SubClass1()

Type Safety and Data Modeling

Sealed classes are useful in data modeling, as they provide better type safety. With sealed classes, you can create a restricted set of types, reducing the probability of runtime errors. They are often used in when expressions, where they help ensure all possible cases are handled:

fun handleSealedClass(myVar: MySealedClass) {
    when (myVar) {
        is SubClass1 -> println("SubClass1")
        is SubClass2 -> println("SubClass2")
    }
}

Code Examples

Example 1: Basic Sealed Class

sealed class Animal {
    class Cat : Animal()
    class Dog : Animal()
}

fun identifyAnimal(animal: Animal) {
    when (animal) {
        is Cat -> println("It's a Cat")
        is Dog -> println("It's a Dog")
    }
}

val myPet: Animal = Animal.Dog()
identifyAnimal(myPet) // Outputs "It's a Dog"

Example 2: Sealed Class with Data

sealed class Result {
    data class Success(val message: String) : Result()
    data class Error(val error: String) : Result()
}

fun handleResult(result: Result) {
    when (result) {
        is Result.Success -> println(result.message)
        is Result.Error -> println(result.error)
    }
}

val res: Result = Result.Success("Operation successful.")
handleResult(res) // Outputs "Operation successful."

Summary

In this tutorial, you learned about sealed classes in Kotlin and how to use them for data modeling. You now know that they can provide better type safety and can be used to represent restricted class hierarchies.

To further your understanding, explore how to use sealed classes with data classes, how to define sealed class hierarchies, and how to use sealed classes with when expressions.

Practice Exercises

Exercise 1

Create a sealed class Shape with two subclasses Circle and Square. Write a function describeShape that takes a Shape and prints a description of the shape.

Exercise 2

Create a sealed class Response with two data subclasses Success and Failure. Each subclass should hold a message. Write a function handleResponse that takes a Response and prints the message.

Exercise 3

Expand on the Animal sealed class from the first example. Add a Bird subclass and update the identifyAnimal function to handle this new subclass.

Remember to test your code and make sure it works as expected. Good luck with your Kotlin journey!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help