Avatar ·

How to initialize an empty MutableList in Kotlin?

Hello everyone! I just started learning Kotlin after Java and encountered a simple but confusing problem.

I need to create an empty mutable list (MutableList) to add elements to it later. In Java I would write something like ArrayList list = new ArrayList<>();. But in Kotlin I see many different ways and don't understand which one is correct.

Here's what I tried:

// Option 1
var list1 = mutableListOf()

// Option 2
var list2: MutableList<String> = mutableListOf()

// Option 3
var list3 = emptyList<String>()

// Option 4
var list4 = ArrayList<String>()

The problem is that:

  • emptyList() returns an immutable list, and I cannot add elements to it.