Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize Kotlin's MutableList to empty MutableList?

Tags:

kotlin

Seems so simple, but, how do I initialize Kotlin's MutableList to empty MutableList?

I could hack it this way, but I'm sure there is something easier available:

var pusta: List<Kolory> = emptyList() var cos: MutableList<Kolory> = pusta.toArrayList() 
like image 463
ssuukk Avatar asked Oct 22 '15 10:10

ssuukk


People also ask

How do you make an empty list on Kotlin?

To create an empty list in Kotlin, we have two ways. One is using listOf() function and the other is using emptyList() function.


1 Answers

You can simply write:

val mutableList = mutableListOf<Kolory>() 

This is the most idiomatic way.

Alternative ways are

val mutableList : MutableList<Kolory> = arrayListOf() 

or

val mutableList : MutableList<Kolory> = ArrayList() 

This is exploiting the fact that java types like ArrayList are implicitly implementing the type MutableList via a compiler trick.

like image 69
Kirill Rakhman Avatar answered Sep 19 '22 21:09

Kirill Rakhman