0

Kotlin – Using Lists

This post shows how to create and use Lists in Kotlin. It will also briefly touch on mutable and immutable lists.

Requirements

  • IntelliJ IDEA Ultimate 2016.3
    • The Community Edition may be enough but we have not tried it.
  • Kotlin Version 1.1
  • Windows 10 Enterprise

Java vs Kotlin Collections

Although Kotlin is 100% interoperable with Java, it does not simply provide wrapped-around-Java-APIs APIs. It has its own set of APIs with some classes that don’t “extend” from Java APIs.

Yes, some other classes “extend” or used directly via typealias. For instance,

The image below shows the Kotlin Collections API.

Using Java Collections API (in Kotlin)

Below is an example that uses java.util.ArrayList.

However, we cannot use the interface java.util.List as the reference type.

It’s best to avoid something like this unless there’s really need for it. Only use classes from Kotlin.

Using Kotlin Collections API

We generally have 2 types of list – immutable and mutable. Immutable lists are lists whose contents we cannot change. We cannot add or remove elements. Mutable lists are the opposite. We can change their contents.

NOTE: Reference list types that don’t have methods to change the contents of the objects they are referring to are essentially immutable. So which reference types make objects immutable? The only way to know is to look into each class or interface to be used provided in Kotlin Collections API.

Here are some codes that are similar to the above codes but using only Kotlin Collections API.

Mutable Lists

Below is an example the uses mutable list. The interface kotlin.collections.MutableList has the add(element: E) method.

Testing a Mutable List Example

Immutable List

Testing a immutable List Example

The following codes demonstrates the use of an immutable list using appropriate factory method and reference type.


References

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert