kotlin
  1. kotlin-listof

Kotlin listOf() Function

The listOf() function is a convenient way to create an immutable list in Kotlin. In this tutorial, we will discuss the syntax, example, output, explanation, use, important points, and summary of the listOf() function in Kotlin.

Syntax

The listOf() function is used to create an immutable list of elements in Kotlin. The syntax of the listOf() function is as follows:

val listName = listOf(element1, element2, ..., elementN)

Where:

  • val is keyword declaring a read-only value.
  • listName is the name of the list.
  • element1, element2, ..., elementN are the elements of the list separated by a comma.

Example

Let's see an example of the listOf() function:

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

Output:

[1, 2, 3, 4, 5]

Explanation

The listOf() function is used to create an immutable list of elements. Once created, the list cannot be modified. The order of the elements is maintained in the list. Each element is separated by a comma and enclosed within parentheses. The listOf() function creates an instance of the List class in Kotlin.

Use

The listOf() function is mainly used to create an immutable list of elements in Kotlin. The elements of the list can be of any data type, including custom data types. The List class provides many useful methods to perform operations on the list, including get(), indexOf(), lastIndexOf(), subList(), contains(), filter(), and many more.

Important Points

  • listOf() function creates an immutable list of elements in Kotlin.
  • The elements in the list can be of any data type.
  • The list cannot be modified once created.
  • List class provides many useful methods to perform operations on the list.

Summary

In this tutorial, we discussed the syntax, example, output, explanation, use, important points, and summary of the listOf() function in Kotlin. The listOf() function is a convenient way to create an immutable list of elements. The List class provides many useful methods to perform operations on the list.

Published on: