

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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]
- Related Questions & Answers
- How to initialize an empty array list in Kotlin?
- How to initialize an array in Kotlin with values?
- How to initialize Kotlin's MutableList to empty MutableList?
- How to initialize a list to an empty list in C#?
- How to declare and initialize a list in C#?
- Java Program to Initialize a List
- How to create a list in Kotlin?
- How to easily initialize a list of Tuples in C#?
- Python - Ways to initialize list with alphabets
- How to clone or copy a list in Kotlin?
- How to convert a List to a Map in Kotlin?
- How to add an item to a list in Kotlin?
- How to initialize variables in C#?
- Why we can't initialize static final variable in try/catch block in java?
- How to initialize an array in Java
Advertisements