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
fruits.add("Orange") // Error: Unresolved reference: add
Comments
Post a Comment
Leave Comment