Kotlin Tutorial 5 — Basic Collections

Nick Apperley
2 min readDec 22, 2016

--

In this tutorial there will be a look at more complex data types that hold a group of data. Along the way immutability will be touched upon in terms of how it fits into Kotlin’s collection types.

Array

To start things off the first collection type to visit is the array (Array). An array in Kotlin is fixed length with the first element starting at position 0. Try the following in the Kotlin REPL:

To add elements to an array a new copy is returned which won’t work on a constant holding an array, but does work if a variable is used. Try the following in the Kotlin REPL to see this in action:

List

Like a array except they can have a variable number of elements, and are the same as a Python list. Elements can not only be added but also removed from a list. Try the following in the Kotlin REPL:

One thing to note about the code above is that a mutable list (MutableList) was created. All of Kotlin’s collection types (except Array) have a mutable and immutable type. Normally if you are using a collection type it is highly preferable to use the immutable version. Immutability is favoured because it ensures that a program is less error prone due to its state remaining consistent, which leads to more predicable behaviour and easier software testing.

Try the following using an immutable list (List) in the Kotlin REPL, and see what happens when an attempt is made to alter (mutate) the list:

Set

Like a list except every element has to be unique, you cannot get an element by position, and existing elements cannot be changed. A Kotlin set is the same as a Python set. Try the following in the Kotlin REPL:

Map

A group of key/value pairs where every key has to be unique. A Python dictionary is the same as a Kotlin map. Try the following in the Kotlin REPL:

Conclusion

You now have a basic understanding of all key collection types. Next tutorial will look at program control flow with conditional statements and loops in Kotlin Tutorial 6 — Control Flow.

TOC

  1. Kotlin Tutorial 1 — Introduction
  2. Kotlin Tutorial 2 — Basic Data Types
  3. Kotlin Tutorial 3 — Basic Operators
  4. Kotlin Tutorial 4 — Handling Input And Output
  5. Kotlin Tutorial 5 — Basic Collections
  6. Kotlin Tutorial 6 — Control Flow
  7. Kotlin Tutorial 7 — Functions
  8. Kotlin Tutorial 8 — Modularity
  9. Kotlin Tutorial 9 — Using An IDE
  10. Kotlin Tutorial 10 — Classes
  11. Kotlin Tutorial 11 — Inheritance
  12. Kotlin Tutorial 12 — Encapsulation And Polymorphism
  13. Kotlin Tutorial 13 — Generics

--

--

No responses yet