- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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 Articles
- How to initialize an empty array list in Kotlin?
- How to initialize an array in Kotlin with values?
- How to initialize a list to an empty list in C#?
- How to declare and initialize a list in C#?
- How to easily initialize a list of Tuples in C#?
- How to create a list in Kotlin?
- Java Program to Initialize a List
- Python - Ways to initialize list with alphabets
- Different ways to initialize list with alphabets in python
- 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#?
- How to get a list of installed Android applications in Kotlin?
- How to create a mutable list with repeating elements in Kotlin?

Advertisements