KOTLIN / CHAPTER 09
Classes and data values
IntermediateModel identity and understand what generated copying does.
By the end of this chapter
- Declare constructor properties
- Use data-class equality
- Recognize shallow copies
The idea
A primary constructor can declare properties directly with val or var. Ordinary classes are useful when an object has identity and controlled behavior. A data class instead generates operations such as equals, toString, and copy from properties in its primary constructor. This makes small data carriers concise, but you must still decide which values are allowed and how mutation should be controlled.
The generated copy operation is shallow. It makes a new outer instance while reusing referenced objects unless replacements are provided. A mutable list held by a property can therefore remain shared between the original and its copy. Prefer immutable components for simple value models, or explicitly copy mutable nested state when independence is required.
data class Badge(val title: String, val points: Int)
fun main() {
val first = Badge("Explorer", 10)
val second = first.copy(points = 15)
println("${first.points}:${second.points}")
println(first == Badge("Explorer", 10))
}10:15 true
copy replaces the requested constructor property in a new instance. Data-class equality compares the declared constructor values, so first equals the matching badge.
Try it yourself
Model an immutable lesson summary using only val properties and produce an updated copy.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING