Command line argumentsIntroduction to KotlinPairs and triplesLists

Lists

To store many objects of the same type, we can use a list:

>>> val L = listOf("CS109", "is", "the", "best")
>>> L
[CS109, is, the, best]
>>> L.size
4
>>> L[0]
CS109
>>> L[3]
best
The type of L is not just List, but List<String>. List is a parameterized type, where the type parameter indicates the type of the objects stored inside the list. Type parameters are given using angular brackets.

Like in Python, the elements of the list can be accessed as L[i] for an index i. The first element has index 0, the last one has index L.lastIndex. The length of the list can be obtained as L.size (and so L.lastIndex == L.size - 1.

You can also use a for-loop to look at the elements of an array one-by-one:

>>> for (e in L)
...   println(e)
CS109
is
the
best
This is called "iterating over the list and is quite similar to the for-loop in Python.

Often we need the indices of the elements while we iterate over this list. This can be done like this:

>>> for (i in L.indices)
...   println("$i: ${L[i]}")
0: CS109
1: is
2: the
3: best

There are many other useful methods of lists:

The joinToString method has a number of options, which are best set as named parameters, for instance:

>>> val a = listOf(1, 2, 3, 4, 5)
>>> a.joinToString()
1, 2, 3, 4, 5
>>> a.joinToString(prefix="{", postfix="}")
{1, 2, 3, 4, 5}
>>> a.joinToString(separator="/")
1/2/3/4/5
>>> a.joinToString(separator="-", prefix="<", postfix=">")
<1-2-3-4-5>

Mutable lists

So far we didn't discuss any way you can change a list—and in fact, you cannot! A List cannot be changed after it was created.

If you want to modify the sequence of elements, like replacing elements, adding elements, or removing elements, you need to use a MutableList.

Again, you can create a mutable list from a given set of elements:

>>> val a = mutableListOf("CS109", "is", "the", "best")
>>> a
[CS109, is, the, best]
If you want to start with an empty list, you need to indicate the type of elements explicitely:
>>> val b = mutableListOf<String>()
>>> b
[]
We can then add elements (of the right type) at the end:
>>> a.add("of")
true
>>> a.add("all")
true
>>> a
[CS109, is, the, best, of, all]
We can also add elements at the front or in the middle of the list, by providing an index for adding:
>>> a.add(0, "Course")
>>> a
[Course, CS109, is, the, best, of, all]
>>> a.add(5, "course")
>>> a
[Course, CS109, is, the, best, course, of, all]

Elements are modified by simply assigning to the index:

>>> a[1] = "CS206"
>>> a
[Course, CS206, is, the, best, course, of, all]

And elements can be removed from the list using removeAt:

>>> a.removeAt(3)
the
>>> a
[Course, CS206, is, best, course, of, all]

A few more useful methods of mutable lists are:

Command line argumentsIntroduction to KotlinPairs and triplesLists