Kotlin listOf

In this guide, we'll dive deep into the listOf() function, exploring its syntax, usage, and providing a a lot's of examples for your better understanding.

What is listOf()? 

In Kotlin, the listOf() function is a part of the standard library, and it's used to create an immutable list. This means that once the list is created using listOf(), you cannot add, remove, or modify elements in the list.

Basic Syntax:

val list: List<Type> = listOf(element1, element2, element3, ...)

Examples with Outputs

Creating a Simple List of Integers

val numbers = listOf(1, 2, 3, 4, 5)
println(numbers)  // Output: [1, 2, 3, 4, 5]

Creating a List of Strings

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

List with Mixed Data Types 

In Kotlin, you can create a list of mixed data types, although it's not a common practice.

val mixed = listOf(1, "Apple", 2.5, 'A')
println(mixed)  // Output: [1, Apple, 2.5, A]

Empty List 

You can also create an empty list using listOf(). The type of the list can be inferred from the context or explicitly mentioned.

val emptyList = listOf<String>()
println(emptyList)  // Output: []

Accessing Elements from the List 

Just like any list in Kotlin, you can access elements by their index.

val colors = listOf("Red", "Green", "Blue")
println(colors[1])  // Output: Green

List of Lists 

Yes, you can have lists inside a list!

val matrix = listOf(
    listOf(1, 2, 3),
    listOf(4, 5, 6),
    listOf(7, 8, 9)
)
println(matrix[1][2])  // Output: 6

Caveats 

Remember, the list you get from listOf() is immutable. So if you try to add an element this will produce an error
fruits.add("Orange")  // Error: Unresolved reference: add
If you need a mutable list, Kotlin offers mutableListOf() which provides a list you can modify.

Conclusion

In this guide, we understood how to use Kotlin's listOf() function with lots of examples. So in Kotlin, listOf() is a handy utility function used to create an immutable list of elements.

Comments