Introduction to Collections in Kotlin

We use collections of objects in every single application, whether it’s business, scientific, or game development. You can pretty much use any collection available in Java directly from within Kotlin. But, Kotlin also offers a few view interfaces over Java collections, which provide a pleasant and a safer coding experience.

For example, Kotlin provides Pair and Triple for a collection of two or three values, respectively. For larger fixed-size collections we can use an array, but for more flexibility we may use lists. We also often use sets and associative maps. Kotlin offers all of them.

Kotlin provides both a mutable and an immutable flavor for collection interfaces that serve as views to Java collections. If the application is simple and single threaded you may use mutable interfaces to access the underlying collections. For more complex behaviors, functional and asynchronous programming, the immutable interfaces are safer to use.

In this chapter, you’ll learn about the different flavors of collections in Kotlin to gain a high-level understanding of what’s there. Then we’ll dive into using Pair, arrays, lists, sets, and maps, both the mutable and immutable versions. We’ll use the facilities for external iteration that we looked at in the previous chapter, and here we’ll see how to use them with collections. With the knowledge you gain from this chapter, you’ll be ready to reach for the right collection for your projects.

Let’s start by looking at different types of collections in the next lesson.

Get hands-on with 1200+ tech skills courses.