Open In App

Kotlin list : listOf()

Last Updated : 15 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Kotlin, a List is a generic, ordered collection of elements. Lists are very common in everyday programming as they allow us to store multiple values in a single variable. Kotlin provides two types of lists - Immutable Lists (which cannot be changed and created using listOf()) and Mutable Lists (which can be modified and created using mutableListOf()).

In this article, we will focus on listOf(), which creates a read-only (immutable) list.

What is listOf() in Kotlin?

The listOf() function is used to create a fixed, immutable list. This means once the list is created, we cannot add, remove, or update its elements.

For Example:

val numbers = listOf(1, 2, 3, 4, 5)

Here, we created an immutable list named numbers containing the integers 1 through 5.

Accessing Elements in listOf()

We can access elements in the list using indexing. The index of the first element is 0 and the last element is list.size - 1.

val firstNumber = numbers[0]             // returns 1
val lastNumber = numbers[numbers.size - 1] // returns 5

In this example, we use indexing to access the first and last elements of the numbers list. Note that indexing is 0-based in Kotlin, so the first element has an index of 0 and the last element has an index of numbers.size - 1.

Iterating Over the List

We can loop through the list using a simple for loop:

for (number in numbers) {
println(number)
}

In this example, we use a for loop to iterate over the numbers list and print each element to the console.

Advantages of listOf()

Here are some advantages of using the listOf() function in Kotlin:

  • Immutability: The listOf() function creates an immutable list, which means that the contents of the list cannot be modified once it has been created. This makes it easier to reason about the behavior of your code and can help prevent bugs caused by unintended changes to the list.
  • Type safety: Since Kotlin is a statically typed language, the listOf() function provides type safety by ensuring that all elements of the list are of the same type. This can help prevent errors caused by passing the wrong type of data to a function or method.
  • Convenience: The listOf() function is a simple and convenient way to create lists of elements in Kotlin. It takes a variable number of arguments, which makes it easy to create a list of elements without having to write a lot of boilerplate code.


Disadvantages of listOf()

Here are some disadvantages of using the listOf() function in Kotlin:

  • Immutability: While immutability can be an advantage in some cases, it can also be a disadvantage in situations where you need to modify the contents of a list during the runtime of your program. If you need to modify a list, you will need to use a mutable list instead of an immutable one.
  • Performance overhead: Immutable lists can have some performance overhead compared to mutable lists or arrays, especially if you need to perform a lot of operations on the list. This is because each operation on an immutable list requires the creation of a new list object, which can be expensive in terms of memory and processing time.
  • Limited functionality: The listOf() function creates a basic immutable list with limited functionality. If you need more advanced features, such as the ability to add or remove elements from the list, you will need to use a mutable list instead.
    Overall, the listOf() function is a useful tool for creating immutable lists of elements in Kotlin, but it is not suitable for every situation. Its
  • Advantages include immutability, type safety, and convenience, while its disadvantages include limited functionality and potential performance overhead. When deciding whether to use listOf() in your code, it's important to consider the specific needs of your program and choose the appropriate data structure accordingly.

Examples of listOf()

A list is a generic ordered collection of elements. Kotlin has two types of lists, immutable lists (cannot be modified) and mutable lists (can be modified). 
Read-only lists are created with listOf() whose elements can not be modified and mutable lists created with mutableListOf() method where we alter or modify the elements of the list.

1. List of Integers: 

Kotlin
fun main() {
    val numbers = listOf('1', '2', '3')
    println(numbers.size)
    println(numbers.indexOf('2'))
    println(numbers[2])
}

Output: 

3
1
3


2. List of Strings: 

Kotlin
fun main() {
    val names = listOf("Ram", "Shyam", "Raja", "Rani")
    println("List size: ${names.size}")
    println("Index of 'Raja': ${names.indexOf("Raja")}")
    println("Element at index 2: ${names[2]}")

    for (i in names.indices) {
        println(names[i])
    }
}

Output: 

List size: 4
Index of 'Raja': 2
Element at index 2: Raja
Ram
Shyam
Raja
Rani


Indexing of Elements of List in Kotlin

Each element of a list has an index. The first element has an index of zero (0) and the last Element has index 
len - 1, where 'len' is the length of the list. 

Example:

Kotlin
fun main() {
    val numbers = listOf(1, 5, 7, 32, 0, 21, 1, 6, 10)

    println(numbers.get(0))
    println(numbers[7])
    println("First index of 1: ${numbers.indexOf(1)}")
    println("Last index of 1: ${numbers.lastIndexOf(1)}")
    println("Last index in list: ${numbers.lastIndex}")
}

Output: 

1
6
First index of 1: 0
Last index of 1: 6
Last index in list: 8


First and Last Elements

We can retrieve the first and the last elements of the list without using the get() method.

Example:

Kotlin
fun main() {
    val numbers = listOf(1, 5, 7, 32, 0, 21, 1, 6, 10)
    println(numbers.first())
    println(numbers.last())
}

Output: 

1
10 


List Iteration methods

It is process of accessing the elements of list one by one. 
There are several ways of doing this in Kotlin.

Example:

Kotlin
fun main() {
    val names = listOf("Gopal", "Asad", "Shubham", "Aditya", "Devarsh", "Nikhil", "Gagan")

    // Method 1: Simple For Loop
    for (name in names) {
        print("$name, ")
    }
    println()

    // Method 2: Using indices
    for (i in 0 until names.size) {
        print("${names[i]} ")
    }
    println()

    // Method 3: Using forEachIndexed
    names.forEachIndexed { index, value ->
        println("names[$index] = $value")
    }

    // Method 4: Using ListIterator
    val it = names.listIterator()
    while (it.hasNext()) {
        print("${it.next()} ")
    }
}

Output: 

Gopal, Asad, Shubham, Aditya, Devarsh, Nikhil, Gagan, 
Gopal Asad Shubham Aditya Devarsh Nikhil Gagan
names[0] = Gopal
names[1] = Asad
names[2] = Shubham
names[3] = Aditya
names[4] = Devarsh
names[5] = Nikhil
names[6] = Gagan
Gopal Asad Shubham Aditya Devarsh Nikhil Gagan


Explanation: 

for (name in names) {
print("$name, ")
}

The for loop traverses the list. In each cycle, the variable 'name' points to the next element in the list. 

for (i in 0 until names.size) {

print("${names[i]} ")
}

This method uses the size of the list. The until keyword creates a range of the list indexes.

names.forEachIndexed({i, j -> println("namess[$i] = $j")})

With the forEachIndexed() method, we loop over the list having index and value available in each iteration. 

val it: ListIterator = names.listIterator()

while (it.hasNext()) {

val i = it.next()
print("$i ")
}

Here we use a ListIterator to iterate through the list.

Sorting the elements in list

The following example show how to sort a list in ascending or descending order. 

Example:

Kotlin
fun main() {
    val list = listOf(8, 4, 7, 1, 2, 3, 0, 5, 6)

    val ascending = list.sorted()
    println(ascending)

    val descending = list.sortedDescending()
    println(descending)
}

Output: 

[0, 1, 2, 3, 4, 5, 6, 7, 8]
[8, 7, 6, 5, 4, 3, 2, 1, 0]

Explanation: 

val asc = list.sorted()

The sorted() method sorts the list in ascending order. 

val desc = list.sortedDescending()

The sortedDescending() method sorts the list in descending order.


Checking Elements: contains() and containsAll() functions

This method checks whether an element exists in the list or not. 

Example:

Kotlin
fun main() {
    val list = listOf(8, 4, 7, 1, 2, 3, 0, 5, 6)

    if (list.contains(0))
        println("List contains 0")
    else
        println("List does not contain 0")

    if (list.containsAll(listOf(3, -1)))
        println("List contains 3 and -1")
    else
        println("List does not contain 3 and -1")
}

Output: 

List contains 0
List does not contain 3 and -1

Explanation:

val res = list.contains(0)

Checks whether the list contains 0 or not and returns true or false (her true) that is stored in res. 

 val result = list.containsAll(listOf(3, -1))

Checks whether the list contains 3 and -1 or not. 


Next Article
Article Tags :

Similar Reads