What is the listOf() method in Kotlin?

The listOf() method in Kotlin is used to create an immutable list. An immutable list is read-onlyIts elements cannot be modified.

Syntax

The listOf() method can be declared as shown in the code snippet below:

fun <T> listOf( vararg elements: T): List<T>
  • elements: The elements to be added to the list.

Return value

The listOf() method returns an immutable list containing the specified elements.

Example

Consider the code snippet below, which demonstrates the use of the listOf() method.

fun main(args: Array<String>) {
val list1 = listOf("aa", "bb", "cc")
println("list1: " + list1)
}

Explanation

The listOf() method is used in line 3 to create an immutable list of the three elements declared as parameters.

Free Resources