Data, Sealed & Value Classes Interview Questions
KOTLIN › Types & Classes
What does a data class give you for free, and what are its restrictions?
What a strong answer covers: The compiler generates equals, hashCode, toString, copy and componentN functions from the properties in the primary constructor. It needs at least one constructor parameter, those must be val or var, and it can't be abstract, open, sealed or inner. Properties declared in the body are ignored by the generated methods.
What is a sealed class or sealed interface, and why is it useful for UI state?
What a strong answer covers: A sealed hierarchy has a closed set of subclasses known at compile time, so a when expression over it is exhaustive without an else branch, and adding a new case breaks compilation everywhere it must be handled. That fits UI state like Loading, Success(data), Error(message), and one-off results or navigation events. Sealed interfaces allow a class to belong to several sealed hierarchies.
Sealed class vs enum: when would you pick each?
What a strong answer covers: An enum has a fixed set of single instances, all with the same shape, good for simple constants like a sort order. A sealed hierarchy lets each case carry different data and have multiple instances, like Success(user) vs Error(throwable). Enums give you values() and ordinal for free; sealed classes give you per-case state.
What is a value class, and when does the wrapper actually get boxed?
What a strong answer covers: A @JvmInline value class wraps a single value to give type safety, like UserId(String), with the wrapper erased at runtime in most cases. It gets boxed when used as a nullable type, as a generic type argument (in collections), or when passed as an interface it implements. Functions taking value classes get mangled names so Java can't easily call them.
What are the pitfalls of data classes with mutable properties or collections, and of using copy() for deep state?
What a strong answer covers: A var property that changes after the object is used as a HashMap key or Set element changes its hashCode and breaks lookups. copy() is shallow, so copying a data class holding a MutableList shares the list, and mutating it changes both 'copies'. In Compose and StateFlow, mutating in place means equals sees no change and nothing updates. A strong answer uses val with immutable collections and copy() for every change.