Kotlin

Lesson 02

Data class immutability

Use immutable data classes and copy when a request creates a new state.

Good Code

src/main/kotlin/reviews/ReviewDraft.kt
data class ReviewDraft(
    val title: String,
    val tags: List<String>,
)

fun rename(draft: ReviewDraft, title: String): ReviewDraft {
    // copy returns the next draft without mutating the caller's value.
    return draft.copy(title = title.trim())
}

Bad Code

ReviewDraft.kt
class ReviewDraft(
    var title: String,
    val tags: MutableList<String>,
)

fun rename(draft: ReviewDraft, title: String) {
    // Shared mutable state changes every reference to this draft.
    draft.title = title.trim()
}

Review Notes

What to review

Good Code

The good version models a review draft as a value and returns the next state through copy.

Bad Code

The bad version exposes var and MutableList, so later code can change the draft without passing through a named operation.

Takeaways

  • Kotlin data classes should protect value state from caller mutation after construction.