Android scenarios, corner cases, and interviews
UI state
Expose List<UiItem>, not MutableList, from ViewModel state. Replace the list when state changes so Compose and diffing can observe a new value.
Paging and large data
Do not load millions of records merely to run an elegant collection chain. Filter in the database/network where possible, page results, and measure transformations.
Corner cases
first()throws on empty collections;firstOrNull()returns null.associateBykeeps the last value when duplicate keys occur.groupBystores lists for all groups and may allocate heavily.- Hash-based collections require stable
equals/hashCodewhile entries are stored. - Sequences are single-pass when backed by an iterator or generator; do not assume replayability.
- Mutable collections shared across coroutines require ownership or synchronization.
Interview questions
Read-only versus immutable?
A read-only reference exposes no mutation methods, but another alias may still mutate the same object. Immutability means the observable value cannot change.
Why is MutableList invariant?
It both returns and accepts elements. Treating MutableList<Dog> as MutableList<Animal> would allow inserting a Cat.
Sequence versus Flow?
A sequence is synchronous lazy iteration. Flow is an asynchronous stream that supports suspension and coroutine cancellation.
Exercises
- Compare
groupByandassociateBywith duplicate keys. - Demonstrate a read-only list changing through a mutable alias.
- Build a producer using
outand a consumer usingin. - Create an observable property delegate.
- Design a DSL that requires essential values outside the receiver block.
Choose collections based on ownership, size, ordering, uniqueness, and update behavior. Expressive chains are valuable only when their allocations and execution remain understandable.