Learn
Lists
List Functions

Every collection in Kotlin contains a series of built-in functions that allow us to perform certain operations in order to retrieve information about the collection or manipulate its values.

A function that retrieves information about a list would only require read access whereas a function that changes the contents of a list would require both read and write access. As a result of this, a mutable list supports functions that possess read and write functionalities, whereas an immutable list supports functions that possess read-only operations. Let’s take a closer look:

Mutable and immutable list functions:

var vowels = listOf('A', 'E', 'I', 'O', 'U')

The contains() function accepts a single value within its parentheses and returns a Boolean true or false depending on whether or not that value exists within a list. It does not need to change the contents of the list, thus it can be used on an immutable list.

println(vowels.contains('A')) // Prints: true println(vowels.contains('B')) // Prints: false

The random() function also only requires read-only access and returns a random element from the list:

println(vowels.random()) // Prints: I

Mutable ONLY list functions:

var primeNumbers = mutableListOf(4, 5, 7, 11, 13)

The add() function accepts a single value within its parentheses and appends that value to the end of a list:

primeNumbers.add(17) println(primeNumbers) // Prints: 4, 5, 7, 11, 13, 17

Since this function changes the contents of the list, it can only be used on mutable lists. Similarly, the remove() function, also only used on mutable lists, accepts a single value within its parentheses and removes it from the list:

primeNumbers.remove(4) println(primeNumbers) // Prints: 5, 7, 11, 13, 17

Note: If the value to be removed does not exist, the compiler will not throw an error and simply return false.

These functions are just the tip of the iceberg of what’s supported for lists in Kotlin; we encourage you to look through the documentation for immutable lists and mutable lists to explore other available functionalities.

Instructions

1.

In Planets.kt, we’ve declared a mutable list containing the names of planets within our solar system. We’ll use Kotlin’s built-in list functions to fix some of its inaccuracies.

First, use the remove() function to delete the planet that does not fit in the list. Check the hint for help.

2.

There is one planet that’s currently missing. On the following line, use the add() function to add it to the list.

Hint: It’s the only planet in the entire solar system with a liquid surface.

3.

Implement the random() function on the following line to generate a random planet from the list. Make sure to wrap your code in a println() statement to see the output.

Run your program multiple times to see the randomly generated values.

Folder Icon

Take this course for free

Already have an account?