# How to really check if a List is Mutable?

**URL:** <https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104>\
**Category:** Uncategorized\
**Created:** [January 11, 2019, 12:10am UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104 "2019-01-11T00:10:19Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![SackCastellon](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/sackcastellon/32/4553_2.png) [@SackCastellon](https://discuss.kotlinlang.org/u/SackCastellon)\
**Post date:** [January 11, 2019, 12:10am UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/1 "2019-01-11T00:10:20Z")

</div>

Is there any way to really check if a list is mutable?

Casting seems not to work as you can see in this example:

```run-kotlin
fun main() {
    val list: List<Int> = listOf(1, 2, 3)
    (list as? MutableList<Int>)?.add(42)
}

```

However, using full reflection I have managed to check it a list is mutable:

```kotlin
import kotlin.reflect.full.allSupertypes

fun main() {
    val l0: List<Int> = emptyList()
    val l1: List<Int> = listOf()
    val l2: List<Int> = mutableListOf()
    val l3: List<Int> = arrayListOf()
    val l4: List<Int> = java.util.ArrayList()
    val l5: List<Int> = java.util.LinkedList()

    l0.isMutable() // false
    l1.isMutable() // false
    l2.isMutable() // true
    l3.isMutable() // true
    l4.isMutable() // true
    l5.isMutable() // true
}

private fun List<*>.isMutable() {
    println(this::class.allSupertypes.any { it.toString() == "kotlin.collections.MutableList<E>" })
}

```

But it doesn’t look pretty and reflection has a high cost in terms of performance.

So, is there any other way to check if a list is mutable?

---

<div class="post-metadata">

**Author:** ![nbness1337](https://avatars.discourse-cdn.com/v4/letter/n/73ab20/32.png) [@nbness1337](https://discuss.kotlinlang.org/u/nbness1337)\
**Post date:** [January 11, 2019, 2:00am UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/2 "2019-01-11T02:00:57Z")

</div>

Just use the type checker `refName is ClassName`. Most, if not all, mutable `List` implementations extend `MutableList`. Or they should…

```auto
fun main() {
    val l0: List<Int> = emptyList()
    val l1: List<Int> = listOf()
    val l2: List<Int> = mutableListOf()
    val l3: List<Int> = arrayListOf()
    val l4: List<Int> = java.util.ArrayList()
    val l5: List<Int> = java.util.LinkedList()

    for (list in arrayOf(l0, l1, l2, l3, l4, l5)) {
        println(list is MutableList)
    }
}

```

prints what you are expecting

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [January 11, 2019, 2:05am UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/3 "2019-01-11T02:05:08Z")

</div>

I don’t think there is any way except reflection that works. The reason casting doesn’t work (as I understand it) is that `List` and `MutableList` don’t actually exist at runtime at least for classes like `ArrayList`. There is some magic there, which makes both of those interfaces compile to `java.util.List`. This is why your read only list seems to implement `MutableList`.  
The way java “solved” read only lists is by just having the read-only lists throw `UnsupportedOperationExceptions`.

> [@nbness1337](#):
>
> Just use the type checker `refName is ClassName` . Most, if not all, mutable `List` implementations extend `MutableList`
> 
> prints what you are expecting

Reading the question helps. He just showed that this does not work 🤦‍♂️ Try `listOf(1, 2, 3)`.

* * *

Looking at the generated byte-code for `list is MutableList` I noticed that there is a special function in `kotlin.jvm.internal.TypeIntrinsics` used to do this.  
Here is it’s current definition

```java
public static boolean isMutableList(Object obj) {
    return obj instanceof List &&
           (!(obj instanceof KMappedMarker) || obj instanceof KMutableList);
}

```

As far as I understand it, this function assumes that all lists implemented in Java are mutable. I guess `KMutableList` and `KMappedMarker` get used (by the kotlin compiler) to mark whether list implementations are mutable or not.  
So I guess the real problem is how to check that java-lists are mutable and I don’t think there is.

---

<div class="post-metadata">

**Author:** ![nbness1337](https://avatars.discourse-cdn.com/v4/letter/n/73ab20/32.png) [@nbness1337](https://discuss.kotlinlang.org/u/nbness1337)\
**Post date:** [January 11, 2019, 2:24am UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/4 "2019-01-11T02:24:03Z")

</div>

Huh, this actually isn’t what I expected to happen, I just kind of assumed that `listOf` returned just a read only `List` because thats what the signature is for `listOf` and `Array.asList()`. Interesting, it seems most if not all lists are compiled to `ArrayList`

---

<div class="post-metadata">

**Author:** ![fatjoe79](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fatjoe79/32/4221_2.png) [@fatjoe79](https://discuss.kotlinlang.org/u/fatjoe79)\
**Post date:** [January 11, 2019, 6:16am UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/5 "2019-01-11T06:16:10Z")

</div>

I am surprised that the reflection solution works. Those Kotlin collection types don’t exist at runtime. 🤔

---

<div class="post-metadata">

**Author:** ![Jonathan.Haas](https://avatars.discourse-cdn.com/v4/letter/j/c68b51/32.png) [@Jonathan.Haas](https://discuss.kotlinlang.org/u/Jonathan.Haas)\
**Post date:** [January 11, 2019, 8:42am UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/6 "2019-01-11T08:42:35Z")

</div>

There is no way, as the Java List implementations don’t show if they’re immutable or not.

If there were an `ImmutableList` interface (like the one of the Guava collections), you could just do `is ImmutableList`, but as it it, with Kotlin that doesn’t work (obviously unless you use Guava in Kotlin).

---

<div class="post-metadata">

**Author:** ![vbezhenar](https://avatars.discourse-cdn.com/v4/letter/v/35a633/32.png) [@vbezhenar](https://discuss.kotlinlang.org/u/vbezhenar)\
**Post date:** [January 11, 2019, 7:46pm UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/7 "2019-01-11T19:46:36Z")

</div>

The only way is to cast to MutableList and modify the collection. If you’ve got UnsupportedOperationException, then the collection was unmodifiable. At least if you care about Java interop. Your code won’t work with Collections.unmodifiableList, for example.

---

<div class="post-metadata">

**Author:** ![SackCastellon](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/sackcastellon/32/4553_2.png) [@SackCastellon](https://discuss.kotlinlang.org/u/SackCastellon)\
**Post date:** [January 11, 2019, 8:18pm UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/8 "2019-01-11T20:18:38Z")

</div>

> [@vbezhenar](#):
>
> The only way is to cast to MutableList and modify the collection.

This could be used after some study as a last resort, but I’m not a fan of it as it would alter the collection being checked.

> [@vbezhenar](#):
>
> Your code won’t work with Collections.unmodifiableList, for example.

In fact, it does work surprisingly.

```auto
import kotlin.reflect.full.allSupertypes

fun main() {
    val l1: List<Int> = java.util.ArrayList()
    val l2: List<Int> = java.util.Collections.unmodifiableList(java.util.ArrayList())

    l1.isMutable() // true
    l2.isMutable() // false
}

private fun List<*>.isMutable() {
    println(this::class.allSupertypes.any { it.toString() == "kotlin.collections.MutableList<E>" })
}

```

---

<div class="post-metadata">

**Author:** ![vbezhenar](https://avatars.discourse-cdn.com/v4/letter/v/35a633/32.png) [@vbezhenar](https://discuss.kotlinlang.org/u/vbezhenar)\
**Post date:** [January 11, 2019, 8:35pm UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/9 "2019-01-11T20:35:56Z")

</div>

> [@SackCastellon](#):
>
> This could be used after some study as a last resort, but I’m not a fan of it as it would alter the collection being checked.

Probably you want to alter it, why else would you want to check? But yes, not general-purpose solution, of course.

> [@SackCastellon](#):
>
> In fact, it does work surprisingly.

That’s surprising indeed, I was sure that it wouldn’t work. Probably they have some kind of white-list for unmodifiable collection types. I wasn’t able to find that code from the first glance, but it should be somewhere and may be it’s possible to reuse it. My point is that in Java the only “marker” for unmodifiable collection is to throw exception, so other than white-listing known unmodifiable collections, there’s no way to tell if some particular class modifiable or not. Well, you could try to extract bytecode for something like `add` method and patern-match it 🙂 Just a crazy thought.

Anyway if your Kotlin code works well enough and you’re sure that its performance is bad, just use cache for `this::class`. Something like `Map<KClass, Boolean?>`.

---

<div class="post-metadata">

**Author:** ![SackCastellon](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/sackcastellon/32/4553_2.png) [@SackCastellon](https://discuss.kotlinlang.org/u/SackCastellon)\
**Post date:** [January 11, 2019, 10:34pm UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/10 "2019-01-11T22:34:45Z")

</div>

After some more testing, I have concluded that this check only returns true for instances of `java.util.ArrayList` or `java.util.LinkedList`:

```auto
fun List<*>.isMutable() = this::class.allSupertypes.any { it.toString() == "kotlin.collections.MutableList<E>" }

```

This means that you can check if a list is mutable by checking if it is an `ArrayList` or a `LinkedList`.  
However, if it is of one of the two types it means it **is mutable** but if it is not it **may or may not be mutable**.

For example, the `com.google.common.primitives.Ints.IntArrayAsList` wraps an array of ints while allowing to set the elements at each position, this list is not an instance of `ArrayList` or `LinkedList` but it is _mutable_.

---

<div class="post-metadata">

**Author:** ![AlexeySoshin](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/alexeysoshin/32/5976_2.png) [@AlexeySoshin](https://discuss.kotlinlang.org/u/AlexeySoshin)\
**Post date:** [January 17, 2019, 10:30am UTC](https://discuss.kotlinlang.org/t/how-to-really-check-if-a-list-is-mutable/11104/11 "2019-01-17T10:30:29Z")

</div>

There was similar question asked on StackOverflow a few months ago, which @yole answered:

> <https://stackoverflow.com/questions/52580173/listof-returns-mutablelist/52591274#52591274>

> The separation between `List` and `MutableList` is an illusion created by the Kotlin compiler. At runtime, Kotlin uses Java collection classes, which only have a single `List` interface containing both read and mutation methods. Compile-time references to `List` and `MutableList` are both compiled to `java.util.List` references. Therefore, **it’s not possible to detect whether a list is a `MutableList` at runtime**.
