Kotlin's Collection Slicing Functions Are a Masterclass in Performance Specialization
Understanding these specialization patterns helps developers write collection-heavy code that avoids accidental O(n²) behavior, especially when chaining operations on large lists or custom iterables. The same runtime type-checking technique is reusable in any performance-sensitive Kotlin library.
Kotlin's collection extraction functions share a common design pattern: they inspect the receiver's runtime type and branch into specialized implementations. A `subList` returns a lightweight view that holds only a reference and an offset, making it an O(1) operation that never copies elements. When `slice` receives a contiguous range, it delegates to `subList` first, then copies the view into a new list via `toList()`.
Functions like `take`, `drop`, and `takeLast` check whether the receiver is a `Collection`, a `List`, or implements `RandomAccess`, and choose between index-based loops, iterator-based traversal, or early-termination paths accordingly. `dropLast` simply reframes the problem as `take((size - n).coerceAtLeast(0))`, reusing the already-optimized `take` logic. `chunked` is a one-liner that delegates to `windowed` with the step equal to the window size and `partialWindows = true`.
The underlying philosophy is that a general API does not require a single general algorithm. Pre-allocating result capacity, breaking early from loops, and selecting traversal strategies based on whether a list supports fast random access all contribute to performance without complicating the public interface.
The standard library's habit of checking `this is RandomAccess` at runtime is a quiet rejection of the idea that one algorithm fits all data structures—and it costs almost nothing to implement.
Reframing `dropLast` as `take` is a small but sharp design move: it avoids duplicating logic and automatically inherits every optimization already built into `take`.
Pre-allocating `ArrayList` capacity with an estimated count is a pattern that appears across nearly every function here, suggesting that reallocation cost is a first-class concern in the stdlib's design.
Reading these implementations makes clear that AI-generated code samples rarely teach the performance branching that separates a correct function from a fast one.