How expensive is `MutableList::toList`? Is it just...
# announcements
h
How expensive is
MutableList::toList
? Is it just basically a toggle or something, or does it have to copy values into a new object? I imagine that perhaps mutable list is a wrapper for list, but i'm not sure
g
It creates a new list a copy values
Mutable list is not a wrapper, it's interface and actual implementatation may be different, by default it is Java ArrayList
h
so dang, it is as expensive as
List::toMutableList
, then
g
Yes, it's exactly the same, all those extensions create new list so possible to use for protective copy
Do you have some specific usecase? Because if you don't need a copy, just use MuyableList directly where you need List
m
I think the convention is that methods starting with
to
will copy all the content to a new structure, while methods starting with
as
will just create a view over the original structure.
👍 4
m
Depending on your use case, you can cast it to
List
or return it as a
List
from a function so the caller only sees the ‘immutable’ interface. I believe it’s an ArrayList (by default) under the covers regardless, and Kotlin merely relies on the interface to ‘control’ access.
2
a
Copy code
SomeClass {
    private val _myList: MutableList<String>? = null
    val myList: List<String>? = _myList
    // do things
}
g
It's not always ArrayList, for example listOf(1) will create SingletoneList under the hood and emptyList() doesn't create new instance, but mostly it's true and ArrayList will be used as implementation of List
💯 2
136 Views