
Still, Kotlin does provide mechanisms for doing useful things with these immutable collections (like filtering values or creating new immutable collections from existing ones).
Immutable collections are covariant, but they’re…well…immutable. But Kotlin strives to avoid all runtime failures, therefore, these mutable collections are invariant. Mutable collections can be read from and written to. Mutability and covariance cannot be achieved in the same Collections interface. If shapesList and rectanglesList didn’t have methods like add() (i.e., no mutability)Įven if type-checks were added to all the write-methods in the Mutable Collections, those type checks would produce their own runtime errors/exceptions…which goes against the Kotlin philosophy of having as much compile-time type safety as possible. If rectanglesList couldn’t be put into a variable with type MutableList in the first place (i.e., no covariance). There are two ways the above error could have been avoided: The mutableListOf() is used to create a list of specific type.The last line would throw a runtime error! This is because the last line is trying to add a Circle to a MutableList. The mutableListOf() function is used to create a general list which can have any object like Integers, Strings, Floats etc. Similar to immutable lists, mutable lists are created using mutableListOf() and mutableListOf() functions. Hence the size of mutable list is not fixed. We can add or remove elements from mutable list after its declaration. The MutableList interface also inherits the Collection interface.
Mutable lists are created using MutableList interface. Sublist from index 1 to 3 Kotlin Mutable List
Let us create list using these two functions: fun main() ") The listOf() is used to create a list of specific type. The listOf() function is used to create a general list which can have any object like Integers, Strings, Floats etc. In Kotlin, we can create immutable list using listOf() and listOf() functions.
We will see them with the help of an example.
It contains many useful functions like contains(), indexOf(), isEmpty() etc. interface in Kotlin: class ArrayList : MutableList, RandomAccess, In fact, if you look at the mutableListOf() Kotlin extension. The List interface inherits the Collection interface. Immutable lists are created using List interface. In Kotlin we can have both a mutable list and an immutable list. The mutable list can be considered as a dynamic array whose size can be changed. The ordered is maintained through indices (same as arrays).Īn element can occur more than one time in a list. In this tutorial we will discuss about Kotlin Lists.