Kotlin Collections :Mastering the “Take” Family in Kotlin
In the world of Kotlin collections, sometimes you don’t need the whole buffet — you just want a specific plate. Whether you need the first few items, the last few, or items that meet a specific condition, Kotlin’s take functions have you covered.
Get Learn To Code Smartly’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s break down take, takeLast, and takeWhile.
1. take(n): The Head-Starter
The take(n) function returns a list containing the first $n$ elements from the collection.
- Best for: Grabbing a preview or limiting results (like “Top 3” scores).
- Edge Case: If $n$ is larger than the collection size, it just returns the whole collection without crashing.
val numbers = listOf("One", "Two", "Three", "Four", "Five")
val firstThree = numbers.take(3)
println(firstThree) // Output: [One, Two, Three]2. takeLast(n): The Closer
As you might guess, takeLast(n) grabs the last $n$ elements.
- Best for: Seeing the most recent entries in a log or the “latest” items added to a list.
- Note: The order of the elements remains the same as they were in the original list.
val numbers = listOf(1, 2, 3, 4, 5)
val lastTwo = numbers.takeLast(2)
println(lastTwo) // Output: [4, 5]3. takeWhile { predicate }: The Conditional Scout
This is where things get interesting. takeWhile doesn't care about a specific number. Instead, it starts at the beginning and keeps taking elements as long as the condition (predicate) is true.
- Crucial Detail: The moment the function hits an element that returns
false, it stops and ignores the rest of the collection, even if later elements satisfy the condition.
val numbers = listOf(2, 4, 5, 6, 8)
val evenStart = numbers.takeWhile { it % 2 == 0 }
println(evenStart) // Output: [2, 4]
// Note: It stops at 5 and doesn't see 6 or 8!Summary
- Use
takefor a fixed amount from the start. - Use
takeLastfor a fixed amount from the end. - Use
takeWhilewhen you need data that meets a criteria until it doesn't.
Happy coding!




