Composing and consuming collections the easy way
The Kotlin standard library provides a number of handy extensions that make collections creation and merging easy and safe. We are going to learn them step by step. Let's assume we have the following Message
class defined:
data class Message(val text: String, val sender: String, val timestamp: Instant = Instant.now())
In this recipe, we are going to create two sample collections containing Message
instances and merge them into one list of Message
objects. Next, we are going to iterate through the list of messages and print their text to the console.
Getting ready
Kotlin standard library provides two basic interfaces which represent collection data structure—Collection
and MutableCollection
, both extending the Iterable
interface. The first one defines an immutable collection that only supports read access to its elements. The second interface allows us to both add and remove elements. There are also more...