Data, Sealed & Value Classes Flashcards
KOTLIN › Types & Classes
- What does the compiler auto-generate for a data class?
- equals(), hashCode(), toString(), copy(), and componentN() functions, all derived from the primary constructor properties.
- Which properties are used by a data class's generated equals()/hashCode()/toString()?
- Only properties declared in the primary constructor. Properties declared in the class body are excluded from all generated functions.
- What are the declaration constraints for a data class?
- The primary constructor needs at least one parameter and every parameter must be val or var. A data class cannot be abstract, open, sealed, or inner.
- Is copy() on a data class a deep or shallow copy?
- Shallow. Referenced objects are shared between the original and the copy, so mutating a shared mutable property affects both.
- What makes a sealed class hierarchy 'restricted', and is a sealed class instantiable?
- All direct subclasses are known at compile time and must live in the same module and package. A sealed class is always abstract (cannot be instantiated) and its constructors are protected or private.
- Why can a 'when' over a sealed type omit the else branch?
- The compiler knows every direct subtype, so it can verify exhaustiveness. If a new subtype is added and not handled, the when stops compiling, catching the gap.
- When would you choose an enum vs a sealed class/interface?
- Use an enum for a fixed set of identical-structure constants. Use a sealed type when the closed set of cases must each carry different properties or state.
- How do you declare a value (inline) class and what is the single hard constraint?
- Annotate with @JvmInline and use the value keyword: @JvmInline value class X(val v: Int). It must hold exactly one property initialized in the primary constructor. It is final and can implement interfaces but cannot extend classes.
- When does a value class get boxed instead of inlined?
- When used as a nullable type, as a generic type argument, or as an interface/supertype. Used directly as its own non-nullable type, it is represented by the underlying value with zero overhead.