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.
Section overview
5 resourcesTeaches 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
- Create a data class
Personwith propertiesnameandage. Create a few instances ofPersonand use thecopy()function. - Create a sealed class
Shapewith subclassesCircle,Square, andRectangle. 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article