I see Kotlin has a List
List geeks = Ar
In this way, you can initialize the List in Kotlin
val alphabates : List<String> = listOf("a", "b", "c")
Just for adding more info, Kotlin offers both immutable List
and MutableList
that can be initialized with listOf
and mutableListOf
. If you're more interested in what Kotlin offers regarding Collections, you can go to the official reference docs at Collections.
Let me explain some use-cases : let's create an immutable(non changeable) list with initializing items :
val myList = listOf("one" , "two" , "three")
let's create a Mutable (changeable) list with initializing fields :
val myList = mutableListOf("one" , "two" , "three")
Let's declare an immutable(non changeable) and then instantiate it :
lateinit var myList : List<String>
// and then in the code :
myList = listOf("one" , "two" , "three")
And finally add some extra items to each :
val myList = listOf("one" , "two" , "three")
myList.add() //Unresolved reference : add, no add method here as it is non mutable
val myMutableList = mutableListOf("one" , "two" , "three")
myMutableList.add("four") // it's ok
There is one more way to build a list in Kotlin that is as of this writing in the experimental state but hopefully should change soon.
inline fun <E> buildList(builderAction: MutableList<E>.() -> Unit): List<E>
Builds a new read-only List by populating a MutableList using the given builderAction and returning a read-only list with the same elements.
Example:
val list = buildList {
testDataGenerator.fromJson("/src/test/resources/data.json").forEach {
add(dao.insert(it))
}
}
For further reading check the official doc.
Both the upvoted answers by Ilya and gmariotti are good and correct. Some alternatives are however spread out in comments, and some are not mentioned at all.
This answer includes a summary of the already given ones, along with clarifications and a couple of other alternatives.
Immutable, or read-only lists, are lists which cannot have elements added or removed.
null
elements.Mutable lists can have elements added or removed.
ArrayList
implementation, use this over mutableListOf()
.val list = LinkedList<String>()
. That is simply create the object by calling its constructor. Use this only if you really want, for example, a LinkedList implementation.listOf top-level function to the rescue:
val geeks = listOf("Fowler", "Beck", "Evans")