Good Code
The good version models a review draft as a value and returns the next state through copy.
Lesson 02
Use immutable data classes and copy when a request creates a new state.
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())
}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()
}The good version models a review draft as a value and returns the next state through copy.
The bad version exposes var and MutableList, so later code can change the draft without passing through a named operation.