The top answers here correctly speak to the difference in Kotlin between read-only List (NOTE: it's read-only, not "immutable"), and MutableList. UPDATE: As of Kotlin 1.3.70, the exact buildList function below is available in the standard library as an experimental function, along with its analogues buildSet and buildMap. Public operator fun us(element: String): List defined in public inline operator fun usAssign(element: String): Unit defined in llections Or without initial value - empty list and without explicit variable type: var users = emptyList().toMutableList()Įrror: Kotlin: Assignment operators ambiguity: Mutable variable with mutable list: var users: MutableList = mutableListOf( User("Tom", 32), User("John", 64) ) users += anotherUser - *it creates new ArrayList and assigns it to users.Or without initial value - empty list and without explicit variable type: var users = emptyList() Mutable variable with immutable list: var users: List = listOf( User("Tom", 32), User("John", 64) ) users += anotherUser (under the hood it's users.add(anohterUser)).Or without initial value - empty list and without explicit variable type: val users = mutableListOf() Immutable variable with mutable list: val users: MutableList = mutableListOf( User("Tom", 32), User("John", 64) ) Immutable variable with immutable (read only) list: val users: List = listOf( User("Tom", 32), User("John", 64) ) Defining a List collection in Kotlin in different ways:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |