https://kotlinlang.org logo
Title
a

am

03/06/2018, 1:38 PM
Hello guys, Can any one please answer the following question https://discuss.kotlinlang.org/t/how-does-tolist-function-works/6905 🙏
1
m

miszmaniac

03/06/2018, 1:39 PM
public fun <T> Iterable<T>.toList(): List<T> {
    if (this is Collection) {
        return when (size) {
            0 -> emptyList()
            1 -> listOf(if (this is List) get(0) else iterator().next())
            else -> this.toMutableList()
        }
    }
    return this.toMutableList().optimizeReadOnlyList()
}
This way:)
it’s extension on collection
a

Andreas Sinz

03/06/2018, 1:43 PM
@am we are not talking about
mutable
vs
immutable
lists. there are no real
ìmmutable
-lists in kotlin yet.
List
is a read-only view of a
MutableList
underneath
a

am

03/06/2018, 1:45 PM
Hey @Andreas Sinz can you more simplify please
a

Andreas Sinz

03/06/2018, 1:53 PM
immutable means that an object cannot change at all. As you've found out,
toList()
creates a
mutableList
and returns an object that implements
List<T>
which has no methods on it to change the underlying
mutableList
, so its a read-only List
toList
only guarantees that you get an object back that implements
List<T>
, using
mutableList()
is just an implementation detail
a

am

03/06/2018, 2:08 PM
Ooh thanks it clears a little air, this will help me in future Thank You @Andreas Sinz