https://kotlinlang.org logo
Title
a

Andrew Gazelka

04/28/2019, 4:17 PM
if I am ever taking in a
List
and expect the contents to be the same, I should create a copy, right? (since the
List
might also be Immutable) ... is there any good way to only copy if it is mutable or would that be too much of a micro-optimization?
additionally, if there is no good way to do this in Kotlin, is there a good way to do this in any other languages?
r

Ryan Benasutti

04/28/2019, 4:41 PM
If you are willing to pull in another dependency, Guava has immutable collections you can use: https://github.com/google/guava I also have a Kotlin library that makes them easier to use: https://github.com/Octogonapus/kt-guava
r

robstoll

04/28/2019, 4:42 PM
to be on the safe side you need to use either an immutable list or make a copy
l

louiscad

04/28/2019, 8:26 PM
There's also kotlinx.collections.immutable, which is probably better than using Guava when you already use Kotlin.
p

pablisco

04/28/2019, 10:23 PM
I need to test it but could do something like this:
fun <T> List<T>.ensureInmutable() = when(this) {
  is MutableList -> this.toList()
  else -> this
}
This is assuming that calls to Java code with a List would assume that is a MutableList (which I'm not 100% sure it does)