How are Kotlin Array's toList and asList different? How are Kotlin Array's toList and asList different? arrays arrays

How are Kotlin Array's toList and asList different?


TL;DR

The list created with asList keeps a reference to the original Array.
The list created with toList/toMutableList is backed by a copy of the original Array.

Explanation

asList

The asList function creates a list that reuses the same Array instance, which implies that changes to the original array also have impact on the List:

val arr = arrayOf(1, 2, 3)val l1 = arr.asList()arr[0] = 4println(l1) // [4, 2, 3]

toList

This isn't the case for toList/toMutableList since the array is copied:

val arr = arrayOf(1, 2, 3)val l2 = arr.toList()arr[0] = 4println(l2) // [1, 2, 3]

The Kotlin source code can be found here.


Basically asList() still maintains a reference to the original Array. That means mutations to that list will also mutate the underlying Array.

toList() is simply copying the values of the Array into a new List, but there is no lingering link afterwards.

For most use-cases, they probably are interchangeable. asList() will likely have slightly better performance (since it isn't performing a copy) and toList() will be a "safe" copy against unexpected mutations.