The Programmers Guide To Kotlin - Collections
Written by Mike James   
Monday, 24 February 2020
Article Index
The Programmers Guide To Kotlin - Collections
Mutable List

You can create a MutableList in the same way as a List:

var a:MutableList<String> = mutableListOf("x","y","z")
var b = MutableList<String>(10,{i->(i.toString())})

The big difference is that you can make the MutableList bigger.

If you are familiar with more permissive languages such as JavaScript you might think that this allows you to reference elements that don't exist. You can't. To add an element beyond what are already there you have to use the add method:

var a:MutableList<String> = mutableListOf("x","y","z")
a.add("k")

which produces ["x","y","z","k"].

The add method adds to the end of the collection by default, but you can insert an element at a specific position. 

For example:

var a:MutableList<String> = mutableListOf("x","y","z")
a.add(1,"k")

produces ["x","k","y","z"]

You can also use the addAll method to add a list of elements in one go. To shrink the collection you can use remove and clear which remove one instance of an element and all of the elements respectively.

The sublist(start,end) method gives you the ability to extract a sub-list.

Unlike other languages there is no support for "slicing notation".

It is important that you don't try to make use of an element that doesn't exist. If you do, the result is a run-time exception. You can check the size of a collection using the size property and the lastindex property.

As well as these basic methods and properties there are a number of extensions that take us well beyond what is available in Java. Notable are the sorting methods, the binary search method, and a set of methods that let you find and count elements. They are all worth knowing about and very straightforward in their use.

As already mentioned List isn't completely immutable.

For example, if you explicitly cast to MutableList then you can change elements:

var a=listOf("x","y","z")
var b:MutableList<String>
b=a as MutableList<String>
b[1]="k"
println(a)

This results in [x,k,z] being printed and immutable List a has been changed.

If you want a List to be immutable make sure it isn't cast to MutableList.

The Collections

The List a good archetypal collection class, but what else do we have?

As in Java there are three types of collection:

  • List

  • Map

  • Set

The List has already been described, and it is an ordered list of elements much like an array.

A Map is a set of key value pairs, sometimes called a dictionary, hash map or associative array in other languages.

A Set is an unordered list which allows you to store values in it as if it was a simple container. The key feature of a Set is that it doesn't allow duplicates.

Let's take a brief look at maps and sets. 

Map

Map<K, out V>
MutableMap<K, V>

Map is one of the most useful collection objects and most sophisticated. You can store a set of key/value pairs and retrieve and store values using the key. Key values have to be unique, and you can only store one value per key. The key is covariant in Map and both types are invariant in MutableMap.

Creating an instance of Map works in the same general way, but there are no constructors. Instead you have to use the mapOf and mutableMapOf builder functions, which create objects that implement the Map or MutableMap interfaces.

For example:

var a=mapOf("a" to 1,"b" to 2)

The to operator is a function that converts the left and right objects into a key/value Pair. You can create your own Pair objects and use them in mapOf if you want to:

var e=Pair("c",3)
var a=mapOf("a" to 1,"b" to 2, e)

To access an element you can use the get(K) and put(K,V) methods. You can also set up a map using:

var b= mutableMapOf<String,Int>()
b.put("a",1)

and so on. 

Set

Set<out E>
MutableSet<E>

Set is an unordered collection that doesn't allow duplicates.

As in the case of Map you cannot call a constructor to create a Set. Instead, there are builder functions setOf and mutableSetOf.

For example:

var a=setOf<String>("a","b","c")

You can use add(E) and remove(E) to add and remove elements.

The only real reason for building and using a set is to keep track of which elements are in it. To do this you generally use the contains(E) method which is common to all collections.

An alternative way of creating a set is:

var a= mutableSetOf<String>()
a.add("a")

If you try and add the same element more than once then you don't generate an exception, but there is still only one instance stored in the set.

In addition to Kotlin supported collection types List, Map and Set, there are also type aliases for the Java types ArrayList, HashMap, HashSet, LinkedHashMap, LinkedHashSet and RandomAccess. These are essentially different implementations of the same collection types and work in the same way. Also notice that currently the Kotlin List is implemented as a Java ArrayList.

Sections not included in this extract:

  • Iterators
  • Sequences
  • Ranges & Progressions

Summary

  • Collections store objects as references and make use of generics to work with any type of object.

  • The base class is Collection, but List and MutableList are the best examples of how collections work.

  • Collections generally have factory methods such as collectionOf to create initialized instances. Some also make use of their constructor and an initialization function.

  • Kotlin collections come in mutable and immutable versions. The immutable version is more like a read-only type than a truly immutable data structure.

  • The other core collection types are maps and sets. Map stores key value/pairs. Set stores objects in no particular order without duplicates.

  • An iterator is an object with at least two methods – next, which returns the next object, and hasNext, which is true if there is a next object.

  • Iterators are used to implement for loops and other basic Kotlin constructs and you can implement custom iterators.

  • Sequences are lazy iterators designed to make functional programming in Kotlin more efficient.

  • Range is a special sort of iterator that has a start and stop value.

  • Progression is a range with a step size, step.

  • You can implement custom ranges and progressions.

 

kotlinlogo

This article is an extract from: 

Programmer's Guide To Kotlin

Now Available as a Print Book

cover

You can buy it from: Amazon

Contents

Some Chapters Already Available On The Web

  1. What makes Kotlin Special (Book Only)
  2. The Basics: Variables, Primitive Types and Functions
  3. Control
  4. Strings and Arrays
  5. The Class & The Object
  6. Inheritance
  7. The Type Hierarchy 
            Extract  Type and its problems
            Extract  Smart Casts
  8. Generics
            Extract Basic Generics
            Extract Covariance & Contravariance
  9. Collections, Iterators, Sequences & Ranges
            Extract     Collections
            Extract Iterators & Sequences
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
            Extract    Annoymous and Lambda Functions
            ExtractInline Functions
  12. Data classes, enums and destructuring
            Extract  Data Classes
            Extract      Enums & Sealed Classes 
            Extract 
         Delegated Properties 
            Extract      Destructuring  **NEW!**
  13. Exceptions, Annotations & Reflection
            Extract Exceptions
            Extract Annotation & Reflection 
  14. Working with Java
            Extract Using Swing  

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on, Twitter, Facebook or Linkedin.

Banner


Google Launches Learn For Developers
08/10/2020

Google has announced the launch of Learn, described as a new one-stop destination for developers to achieve the knowledge and skills needed to develop software with Google's technology.



Lightstep Adds New GitHub Action
22/10/2020

Lightstep has announced a new GitHub action, Lightstep Pre-Deploy Check, designed to help developers be proactive about ensuring the quality and performance of their software before it’s actually de [ ... ]


More News

square

 



 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:1871962536>

<ASIN:1871962544>

 



Last Updated ( Monday, 24 February 2020 )