Kotlin / Data Classes and Sealed Classes

Comparing Data and Sealed Classes in Kotlin

In this tutorial, we will compare data classes and sealed classes in Kotlin. You'll learn the different purposes they serve and when to use each in your coding projects.

Tutorial 5 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.

1. Introduction

In this tutorial, we aim to understand and differentiate between data classes and sealed classes in Kotlin. You will learn about the different purposes they serve, and when to use each one in your programming tasks.

By the end of this tutorial, you'll know:
- What data classes and sealed classes are in Kotlin
- The differences and similarities between them
- Practical use cases for each

No specific prerequisites are required for this tutorial. However, basic knowledge of Kotlin syntax and object-oriented programming would be beneficial.

2. Step-by-Step Guide

Kotlin Data Classes

A data class in Kotlin is a concise way to define a class that is used to hold data. The data keyword is used to define a data class.

data class User(val name: String, val age: Int)

In a data class, hashCode(), equals(), toString(), copy(), and componentN() functions are automatically generated.

Kotlin Sealed Classes

Sealed classes are used to represent restricted class hierarchies. They allow you to represent a fixed number of known subclasses. The sealed keyword is used to define a sealed class.

sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()

In a sealed class, subclasses are declared in the same file as the sealed class itself. This allows you to know all possible subclasses.

3. Code Examples

Example 1: Data Class

data class Book(val name: String, val author: String)

fun main() {
    val book1 = Book("Kotlin for Beginners", "John Doe")
    println(book1)
    // Output: Book(name=Kotlin for Beginners, author=John Doe)
}

In this example, a data class Book is created with two properties: name and author. The toString() method is automatically generated and used in the println() function.

Example 2: Sealed Class

sealed class Operation {
    data class Add(val value: Int) : Operation()
    data class Subtract(val value: Int) : Operation()
    object Multiply : Operation()
    object Divide : Operation()
}

fun execute(op: Operation, int1: Int, int2: Int): Int = when (op) {
    is Operation.Add -> int1 + int2
    is Operation.Subtract -> int1 - int2
    is Operation.Multiply -> int1 * int2
    is Operation.Divide -> int1 / int2
}

In this example, a sealed class Operation is created with four subclasses. The when expression is used with the sealed class instance to execute different operations.

4. Summary

In this tutorial, we learned that data classes in Kotlin are primarily used to hold data, and they automatically generate utility functions. On the other hand, sealed classes define a limited class hierarchy, allowing us to model our domain with precision.

The next step could be exploring more about other Kotlin classes like enum classes and abstract classes. For additional resources, consider reading the official Kotlin documentation or the book "Kotlin in Action" by Svetlana Isakova and Dmitry Jemerov.

5. Practice Exercises

  1. Create a data class Person with properties name and age. Create a few instances of Person and use the copy() function.
  2. Create a sealed class Shape with subclasses Circle, Square, and Rectangle. Write functions to calculate the area of each shape.

Remember, practice is the key to mastering any concept. Keep experimenting with different use cases and scenarios. Happy coding!

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

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

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