Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

mutablelistof
kotlin
list
communitycreator

What is the mutableListOf method in Kotlin?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

Overview

In Kotlin, the mutableListOf method is used to create a MutableList, which is a collection of elements that supports adding and removing elements. Using this method, we can:

  1. Create an empty MutableList.
  2. Create a MutableList with elements.

Syntax

// empty MutableList
fun <T> mutableListOf(): MutableList<T>
Creating empty list

Parameters

This method takes no parameters.

Return value

It returns an empty MutableList object.

Syntax to create MutableList with elements

// MutableList with elements
fun <T> mutableListOf(vararg elements: T): MutableList<T>
Creating list with elements

Parameters

The parameters for this method are the elements to be included in the MutableList.

Return value

It returns a MutableList object with the provided arguments as elements.

Example

fun main() {
val mutableList1 = mutableListOf<Int>()
println("mutableList1 : $mutableList1");
val mutableList2 = mutableListOf(1,2,3,4,5);
println("mutableList2 : $mutableList2");
}
Using mutableListOf method to create an MutableList

Explanation

  • Line 2: We use the mutableListOf method to create an empty MutableList object. This object can have Int type values as elements.

  • Line 5: We use the mutableListOf method to create a MutableList object with five Int values 1,2,3,4,5. This method returns a MutableList object with the provided arguments as elements.

RELATED TAGS

mutablelistof
kotlin
list
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring