Kotlin 2.x, KSP & Collections Flashcards
KOTLIN › Modern Kotlin
- What is the K2 compiler and when did it become stable and default?
- A complete rewrite of Kotlin's frontend (FIR-based) handling semantic analysis, call resolution, and type inference on a unified data structure, reusing the shared JVM/JS IR backends. It is Stable and the default compiler since Kotlin 2.0.0.
- Why is KSP faster than kapt?
- kapt generates intermediate Java stub classes and runs the Java annotation processor (javac/apt) over them. KSP reads Kotlin symbols directly from the compiler with no stub-generation round trip, so it is roughly up to twice as fast. kapt is now in maintenance mode.
- What can a KSP SymbolProcessor NOT do?
- It is read-only: it can generate new files but cannot modify existing source. It models declarations (classes, members, functions, parameters) but cannot inspect expressions or statements inside function bodies.
- What is the difference between a read-only List and an Array in Kotlin?
- An Array has a fixed size set at creation and is not a Collection type. A List is a Collection interface; its mutable form (MutableList, default ArrayList) supports dynamic resizing via add/remove. Arrays compile to JVM primitive or object arrays.
- Are Kotlin read-only collections (List, Set, Map) immutable?
- No. They are read-only interfaces (restricted views) that simply expose no mutators. The underlying object may be a MutableList and can still change elsewhere. For genuine immutability use kotlinx.collections.immutable.
- Why are read-only collections covariant but mutable collections invariant?
- List<T> only produces T (out position), so List<Cat> is safely a List<Animal>. MutableList<T> consumes T via add() (in position); allowing covariance would let you insert a Dog into a List<Cat>, so it must stay invariant.
- Does assigning a MutableList to a val make it immutable?
- No. val only fixes the reference so you cannot reassign the variable, but you can still add, remove, and update elements. To prevent mutation, expose it as a read-only List type or use an immutable collection.
- How does the K2 compiler improve smart casts?
- It propagates smart casts in more cases: captured local variables, after a || with type checks (smart-cast to the common supertype), inside inline-function lambdas, on nullable function-type properties, and after increment/decrement operators.
- What are context receivers / context parameters in Kotlin, and what is their status?
- An experimental feature letting a declaration require contextual values in scope via context(...), without explicit parameters or an extension receiver. The original context receivers (-Xcontext-receivers) were replaced in Kotlin 2.2 by context parameters (-Xcontext-parameters); both remain experimental.