Top 10 Kotlin scenario questions
Try each one yourself first, then open the model answer.
1. A crash occurs although Kotlin has null safety. How can that happen?
Show answerHide answer
Common causes are the !! operator, uninitialised lateinit properties, and values from Java code. Handle them with safe calls, defaults and validation at the boundary.
2. A network call on the main thread freezes the app. How do you fix it with coroutines?
Show answerHide answer
Launch a coroutine in a lifecycle-aware scope and do I/O on Dispatchers.IO, then update the UI on the main dispatcher.
3. A coroutine keeps running after the user leaves the screen. What is wrong?
Show answerHide answer
It was started in a scope that outlives the screen, such as GlobalScope. Use viewModelScope or lifecycleScope so cancellation is automatic.
4. One failing child coroutine cancels all its siblings. What if that is not wanted?
Show answerHide answer
Use supervisorScope or a SupervisorJob and handle each child's errors separately.
5. A CPU-heavy loop ignores cancellation. Why?
Show answerHide answer
Cancellation is cooperative. Check isActive or call ensureActive or yield inside the loop.
6. You need to represent loading, success and failure states. What would you use?
Show answerHide answer
A sealed class or sealed interface, so a when expression must handle every case.
7. Two data objects with equal content should be equal. What do you declare?
Show answerHide answer
A data class, which generates equals, hashCode and copy from the primary constructor properties. Properties declared in the body are not included.
8. A chain of list operations on a very large collection is slow. What can help?
Show answerHide answer
Use sequences for lazy, single-pass processing when there are several steps or early termination.
9. You want to add behaviour to a class you cannot modify. How?
Show answerHide answer
Write an extension function. It is resolved statically and cannot access private members.
10. A stream of values must update the UI only while it is visible. What would you do?
Show answerHide answer
Expose a StateFlow or Flow and collect it with lifecycle awareness, for example using repeatOnLifecycle.
