Data classes hold values: the compiler writes equals, hashCode, toString, copy, and destructuring for constructor properties. Sealed classes (and sealed interfaces) restrict subtypes so when is exhaustive — a better UI/network state machine than boolean pairs like isLoading + error.
This Kotlin cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- data class:
data class User(val id: Int, val email: String)—valproperties in the primary constructor. - copy:
user.copy(email = "new@x.com")— immutable updates. - equals: Structural for data classes. Two copies with the same fields are equal.
- Destructure:
val (id, email) = userfollows constructor order. - sealed class: Subtypes in the same compilation unit (relaxed in later Kotlin). Cannot construct the base.
- sealed interface: Same exhaustiveness, multiple inheritance of type.
- when: No
elserequired when every sealed subtype is handled. - enum vs sealed: Enum = fixed constants. Sealed = each subtype can carry different fields.
Copy-paste examples
UiState as a sealed class
Each screen state is a type. The UI when will not compile if you add a new state and forget a branch.
data class Project(val id: Int, val title: String)
sealed interface UiState {
data object Loading : UiState
data class Ready(val project: Project) : UiState
data class Error(val message: String) : UiState
}
fun label(state: UiState): String = when (state) {
UiState.Loading -> "Loading"
is UiState.Ready -> state.project.title
is UiState.Error -> state.message
}Common mistakes
- Putting mutable
varlists inside data classes and mutating them soequalslies. - Using data classes for entities with identity where you only wanted a bag of fields in a Map.
- Open class hierarchies instead of sealed when the set of types is closed.
copy()on a huge object graph as a substitute for a real reducer — still shallow on nested refs.
FAQ
- Can a data class extend another data class? No. They can implement interfaces. Nest them or extract shared interfaces.
- data object? A singleton object with a sane
toString/equals, useful as a sealed state with no fields (Loading).
- Why is BLOGPH0 shallow? It copies constructor args. If a property is a mutable list, both copies share it. Prefer immutable lists.
Related Kotlin cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds mobile app development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.