Sling Academy
Home/Kotlin/Creating Immutable Lists with `listOf` in Kotlin

Creating Immutable Lists with `listOf` in Kotlin

Last updated: December 04, 2024

Kotlin, a statically typed language for the JVM, provides powerful functionality to work with collections, particularly lists. One of the fundamental aspects of Kotlin is its support for immutable collections. An immutable list is a collection of items that once created cannot be altered — no items can be added, removed, or updated in an immutable list.

The simplest way to create an immutable list in Kotlin is by using the listOf function. This approach is very useful when you need a fixed collection of items that you know will not change throughout the lifecycle of your application. This immutability ensures thread-safety and is highly adaptable for functional programming styles.

Why Use Immutable Lists?

Immutable lists have several advantages:

  • Thread-safety: No locks or synchronization is required when reading from an immutable list. All threads see the same data, so concurrency issues are avoided.
  • Safer code: Since the data cannot change, you won’t encounter bugs due to unexpected changes in the list.
  • Ease of understanding: Functions that take immutable data are easier to reason about because you know exactly what those functions are operating on.

Creating Immutable Lists with listOf

The Kotlin standard library provides multiple ways to create immutable lists, with listOf being the simplest and most common.

val fruits = listOf("Apple", "Banana", "Cherry")

In the code snippet above, fruits is an immutable list holding three string items: "Apple", "Banana", and "Cherry". Once this list is created, its size and the elements contained within it cannot be modified. Any attempts to alter its size, such as removing an item, will result in a compile-time error.

Accessing Immutable List Elements

Even though Kotlin lists created with listOf are immutable, you can still access their elements just like any regular list:

println(fruits[0]) // Output: Apple
println(fruits[1]) // Output: Banana
println(fruits[2]) // Output: Cherry

Each element can be accessed via zero-based index.

Iterating Over Immutable Lists

Iterating over an immutable list is straightforward and can be done using loops:

for (fruit in fruits) {
    println(fruit)
}

This loop will print each fruit in the fruits list to the console:

  • Apple
  • Banana
  • Cherry

Immutable Collections and Copying

While you cannot modify an immutable list, you can always create a modified copy of it:

val moreFruits = fruits + "Orange"
println(moreFruits) // Output: [Apple, Banana, Cherry, Orange]

The resulting moreFruits is a new immutable list created by adding "Orange" to the original fruits list. The original list remains unchanged.

Conclusion

Immutable lists in Kotlin offer a powerful tool in the programmer’s arsenal for creating safe and predictable code. Leveraging listOf ensures the data remains consistent and not prone to unforeseen modifications, thus facilitating the principles of functional programming and multi-threaded operations. As Kotlin continues to grow in popularity, understanding and employing immutable collections wisely is an essential skill for developers.

Next Article: Kotlin - Working with Mutable Lists Using `mutableListOf`

Previous Article: Working with Multidimensional Arrays in Kotlin

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin