L P
L P

Reputation: 3

Kotlin List and MutableList: two different references, pointed to the same collection object

Could you give an example to this quotation:

A key thing to keep in mind when working with collection interfaces is that read-only collections aren’t necessarily immutable. If you’re working with a variable that has a read-only interface type, this can be just one of the many references to the same collection. Other references can have a mutable interface type

I want to write a function that adds elements to some collection, while creating a val someCollection: List <> in the fun main(). I can do this through the var someCollection: List <> = funAdd(someCollection.toMutable), but can I do it like this without using a variable var?

Example

fun addEl(numbers:MutableList<Int>):List<Int>{
    for (i in 1..10){
        numbers.add(i)
    }
    return numbers.toList()
}

fun main(args: Array<String>){
    var readOnlyNumbers: List<Int> = emptyList()
    readOnlyNumbers = addEl(readOnlyNumbers.toMutableList())
    println(readOnlyNumbers.size)
}

Can I avoid using var and reassigment readOnlyNumbers or not?

Upvotes: 0

Views: 1515

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170733

To answer this part:

Could you give an example to this quotation:

A key thing to keep in mind when working with collection interfaces is that read-only collections aren’t necessarily immutable. If you’re working with a variable that has a read-only interface type, this can be just one of the many references to the same collection. Other references can have a mutable interface type

This is simply talking about situations like this:

val mutableList: MutableList<Int> = mutableListOf<Int>()
val list: List<Int> = mutableList
println(list) // []
mutableList.add(0)
println(list) // [0]

Even though list has type List<Int> and not MutableList<Int>, its contents have changed.

Note that this is an example of

I want to write a function that adds elements to some collection, while creating a val someCollection: List <> in the fun main().

as well, but I wouldn't recommend writing this code; go with one of JB Nizet's versions.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

Here are various ways of rewriting your code without using var:

fun addEl(numbers:MutableList<Int>):List<Int>{
    for (i in 1..10) {
        numbers.add(i)
    }
    return numbers.toList()
}

fun main(args: Array<String>){
    val readOnlyNumbers: List<Int> = addEl(mutableListOf())
    println(readOnlyNumbers.size)
}

or simply

fun createEl(): List<Int> {
    return (1..10).toList()
}

fun main(args: Array<String>){
    val readOnlyNumbers = createEl()
    println(readOnlyNumbers.size)
}

Upvotes: 1

Related Questions