Design Converter
Education
Software Development Executive - III
Last updated on Aug 23, 2024
Last updated on Aug 23, 2024
Kotlin, a modern programming language that runs on the Java Virtual Machine, offers many features that make coding more concise and expressive. One such feature is the kotlin chunked function, which is part of the Kotlin standard library. This function is incredibly useful when you need to retrieve collection parts or process elements in smaller, more manageable groups.
In this blog, we will explore the chunked function in detail, including how it works, its applications, and some practical examples.
In Kotlin, collections are a fundamental part of the language. They hold all the elements that you work with, such as numbers, strings, or custom objects. Sometimes, you may want to divide these collections into smaller parts or chunks. This is where the kotlin chunked function comes into play. It is an extension function that allows you to split a collection into a list of chunks, each of a given size.
The chunked function takes a single argument, the chunk size, which determines the number of elements each chunk will contain. It is important to note that the last chunk may have a smaller size if the collection does not divide evenly by the chunk size. This function is particularly useful when you need to process large collections in a more efficient and organized manner.
The chunked function in Kotlin can be applied to different types of collections such as lists, sequences, and strings. Here’s the basic syntax:
1fun <T> Iterable<T>.chunked(size: Int): List<List<T>>
The function takes a single argument, size, which determines the number of elements in each chunk. The result is a list of lists, where each inner list contains a portion of the original collection.
Let's explore a basic example using a list of numbers:
1fun main() { 2 val numbers = (1..10).toList() 3 val chunkedNumbers = numbers.chunked(3) 4 println(chunkedNumbers) 5}
Output:
1[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
Here, the numbers list is divided into chunks of three. The last chunk contains fewer elements because the total number of elements is not evenly divisible by the chunk size.
1fun main() { 2 val words = "KotlinChunkedFunction" 3 val stringChunks = words.chunked(5) 4 println(stringChunks) 5}
Output:
1[Kotlin, Chunk, edFun, ction]
In this code, words is a string. By calling chunked with a chunk size of 5, the resulting list of string chunks will be [Kotlin, Chunk, edFun, ction]. As with lists, the last chunk can be of a smaller size if the string's length is not a multiple of the chunk size. The return type of the chunked function is List<String>
. Thus, the variable stringChunks is of type List<String>
.
The chunked function has an overload that allows you to apply a transformation to each chunk after splitting the collection.
1fun <T, R> Iterable<T>.chunked(size: Int, transform: (List<T>) -> R): List<R>
Consider a scenario where you want to split a list of names into pairs and then transform each pair to uppercase:
1fun main() { 2 val names = listOf("Alice", "Bob", "Charlie", "David", "Eva", "Frank") 3 val chunkedNames = names.chunked(2) { it.map(String::uppercase) } 4 println(chunkedNames) 5}
Output:
1[[ALICE, BOB], [CHARLIE, DAVID], [EVA, FRANK]]
In this example, the chunked function splits the list into pairs and then applies the uppercase transformation to each chunk.
One important aspect to consider when using the chunked function in Kotlin is how it handles empty lists. If you attempt to call chunked on an empty list without explicitly specifying the type of elements in the list, you may encounter a type inference error, as shown in the image. This occurs because Kotlin's type inference system cannot determine the type of the elements when the list is empty, leading to ambiguity in the overloaded println function.
Example:
1fun main() { 2 val names = listOf() 3 val chunkedNames = names.chunked(2) 4 println(chunkedNames) 5}
In this example, Kotlin cannot infer the type of elements in the empty names list, which causes a compilation error. To avoid this issue, you can explicitly specify the type of the list, like this:
1fun main() { 2 val names: List<String> = listOf() 3 val chunkedNames = names.chunked(2) 4 println(chunkedNames) 5}
By specifying the type as List<String>
, Kotlin knows how to handle the empty list, and the code will compile and run correctly, producing an empty list of chunks as expected.
One important aspect to consider is how the chunked function handles collections when the total number of elements is not evenly divisible by the chunk size. The last chunk may have fewer elements, and in some cases, it might be empty if the chunk size exceeds the number of remaining elements. In some cases, the last chunk may have fewer elements than the specified chunk size if there aren't enough remaining elements. However, no chunk will ever be empty.
1fun main() { 2 val numbers = (1..5).toList() 3 val chunkedNumbers = numbers.chunked(3) 4 println(chunkedNumbers) 5}
Output:
1[[1, 2, 3], [4, 5]]
Here, the last chunk contains only two elements because only two elements remain after creating the first chunk of three elements.
In addition to chunked, Kotlin provides another function for working with element ranges within a collection: the windowed method. This function is used to retrieve collection parts that represent a sliding window of a given size over the collection. It is similar to chunked but instead of non-overlapping chunks, it creates overlapping windows starting at each element.
1fun main() { 2 val numbers = (1..10).toList() 3 val windows = numbers.windowed(3, step = 1, partialWindows = false) 4 println(windows) 5}
In this example, val numbers is a list of integers from 1 to 10. The windowed method is called with a window size of 3. The resulting list will be [[1, 2, 3], [2, 3, 4], [3, 4, 5], ..., [8, 9, 10]]. Each window contains a range of three adjacent elements, and the windows overlap by two elements.
While both chunked and windowed deal with dividing a collection into smaller parts, they serve different purposes. Chunked is used to divide a collection into non-overlapping chunks of a specified number, while windowed creates overlapping windows starting at each index, allowing you to examine adjacent elements and their possible ranges.
Kotlin's chunked function can also be used lazily when dealing with sequences. This means that the chunks are not created until they are needed, which can be more memory-efficient for large datasets.
1fun main() { 2 val sequence = (1..100).asSequence() 3 val chunkedSequence = sequence.chunked(10) 4 println(chunkedSequence.take(2).toList()) 5}
Output:
1[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]]
Using sequences, the chunked function ensures that only the required chunks are generated, making the process more efficient.
In this article, we explored the chunked function in Kotlin, detailing its purpose, syntax, and various use cases. We looked at how chunked can efficiently split collections, sequences, and strings into smaller, manageable parts, and how it compares to other functions like windowed.
By mastering chunked, you can significantly enhance your data processing capabilities in Kotlin, making your code more efficient and easier to manage. This article should serve as a comprehensive guide to understanding and applying the chunked function effectively in your Kotlin projects.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.