Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to initialize List in Kotlin?
List
List
Example – Initialize List ~ Immutable List
Once a list is declared as Immutable, then it becomes read-only.
fun main(args: Array<String>) {
var myImmutableList = listOf(1, 2, 3)
// Convert array into mutableList
// Then, add elements into it.
myImmutableList.toMutableList().add(4)
// myImmutableList is not a mutable List
println("Example of Immutable list: " + myImmutableList)
}
Output
In this example, we have declared an immutable list called "myImmutableList" and we have printed the same after adding a value in it.
Example of Immutable list: [1, 2, 3]
Example – Initialize List ~ Mutable List
We can modify the values of a mutable list. The following example shows how to initialize a mutable list.
fun main(args: Array<String>) {
val myMutableList = mutableListOf(1, 2, 3)
myMutableList.add(4)
println("Example of mutable list: " + myMutableList)
}
Output
It will produce the following output −
Example of mutable list: [1, 2, 3, 4]
Advertisements
