
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to initialize List<T> in Kotlin?
List<T> denotes a List collection of generic data type. By <T>, we understand that the List does not have any specific data type. Let's check how we can initialize such a collection in Kotlin.
List<T> can be of two types: immutable and mutable. We will see two different implementations of initializing List<T>.
Example – Initialize List<T> ~ 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<T> ~ 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