call of java mutator sort on immutable kotlin collection

Viewed 114

Getting "call of java mutator sort on immutable kotlin collection" as a warning in Android Studio. What could be the reason behind it and how can I resolve it ?

My code looks like this:

 @Test
fun test_Sorting() {
    val longs = listOf(10, 9, 7, 3, 2, -1, 5, 1, 65, -656)
    val uniqueList = UniqueArrayList.from(longs)
    Collections.sort(longs) // **getting the warning on this particular line**
    uniqueList.sort()
    assertListEquals(longs, uniqueList)
}
1 Answers

Kotlin has two types of list

  • The read-only List interface (Java doesn't have this)
  • The MutableList interface, a subtype of List and equivalent with Java's List.

In Kotlin, you cannot mutate a read-only List because it doesn't have any exposed functions for doing so. But if you pass it to a Java-defined method, the compiler will automatically cast it to Java's mutable List interface for interoperability purposes.

The warning is telling you that you are accidentally mutating a List that should be read-only. This can create bugs if your code elsewhere assumes that this List will not be mutated, which is generally a safe assumption for whatever scope of code generated the list.

In this particular case, the code will actually succeed at runtime because the underlying list returned by listOf() with multiple values is actually an ArrayList, which is mutable, but has been upcast to read-only List. However, some of the ways of creating a read-only List in Kotlin produce truly immutable lists that will throw an exception if you try to mutate them.

The warning message is actually misleading, and in my opinion should be rephrased to say "read-only List" instead of "immutable List"

If you want to safely be able to sort a List in Kotlin, you must declare it as mutable to begin with:

val longs = mutableListOf(10, 9, 7, 3, 2, -1, 5, 1, 65, -656)
Related