Kotlin
Summary - Data class
Combine data class, copy and destructuring to write a User model.
Summary - Data class
In this group you learned the data class definition, copying with copy, automatic equals and hashCode, the toString format and splitting into components with destructuring.
Now you will combine them: define a data class, modify it with copy and split it with destructuring. This structure is the foundation of data modeling and transfer in Kotlin. Later, sealed classes and generics will build on it.
Exercise Combine the User model
Define a data class named User with a primary constructor taking val name: String, val age: Int, val email: String. In main create a User("Alex", 30, "alex@x.com") instance. Produce a v instance with u.copy(age = 31). Split u into name, age and email with destructuring. Print name, age and v separately with println.
Show example solution
data class User(val name: String, val age: Int, val email: String)
fun main() {
val u = User("Alex", 30, "alex@x.com")
val v = u.copy(age = 31)
val (name, age, email) = u
println(name)
println(age)
println(v)
}
What comes next?
You learned data classes. In the next groups you will explore closed hierarchies with sealed classes, exhaustive branching with when and singletons with object.
This group combined data class, copy, equals, toString and destructuring. These are the core of Kotlin data modeling. Next you will see safe inheritance patterns with closed hierarchies.
Exercise The Money data class with an add method
Define a data class named Money with a primary constructor taking val amount: Double, val currency: String. Add a method fun add(other: Money): Money whose body returns Money(amount + other.amount, currency). In main create Money(100.0, "USD") and Money(50.0, "USD") instances, sum them with add and print the result.
Show example solution
data class Money(val amount: Double, val currency: String) {
fun add(other: Money): Money {
return Money(amount + other.amount, currency)
}
}
fun main() {
val a = Money(100.0, "USD")
val b = Money(50.0, "USD")
val c = a.add(b)
println(c)
}
Test yourself
-
Which of the following is not auto-generated in a data class?
- equals
- hashCode
- toString
- factory method
Show answer
factory method — A factory method is not auto-generated; you write it yourself in a companion object.
-
Complete the copy call
val v = u.____(age = 31)
Show answer
val v = u.copy(age = 31)
Next lesson: Module design