Creating lists
- Kotlin course
- Beginner
- Lesson 59/116
- 4 min
Learn to create lists with listOf and mutableListOf.
Creating lists: listOf and mutableListOf
Kotlin has two kinds of lists. listOf returns a read-only list: you can read its elements but you cannot add or remove. mutableListOf gives you a mutable list.
val names = listOf("Ava", "Liam")
val nums = mutableListOf(1, 2, 3)
nums.add(4)The type is usually inferred: listOf("a") becomes a List<String>. The list length comes from size; an element is reached with [i] or get(i).
Read-only vs mutable lists
Calling add on a list built with listOf is a compile error, because the returned type is List<T> and has no add method. mutableListOf returns MutableList<T>.
val a = listOf(1, 2) // List<Int>
val b = mutableListOf(1, 2) // MutableList<Int>
b.add(3) // ok
a.add(3) // compile errorThis distinction guarantees at compile time whether a list can be changed later, which makes the code safer.
Practice Print a mutable list of three names
Create a MutableList<String> of three names and print it with println.
Starter code
fun main() {
// Create a mutable list of three names and print it
}Sample solution
fun main() {
val names = mutableListOf("Ava", "Liam", "Nora")
println(names)
}Expected output
[Ava, Liam, Nora]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one creates a mutable list of Int?
- listOf(1, 2, 3)
- mutableListOf(1, 2, 3) Correct answer
- list(1, 2, 3)
- arrayOf(1, 2, 3)
Explanation: mutableListOf returns a mutable list; add and remove work.
2 Fill in the blank: mutable list
val numbers = ____(1, 2, 3)
val numbers = mutableListOf(1, 2, 3)
Explanation: mutableListOf(1, 2, 3) gives a list you can add to.
3 Match list expression to behavior
| Term | Meaning |
|---|---|
listOf(...) |
Read-only list |
mutableListOf(...) |
Mutable list |
size |
Element count |
[i] |
Index access |