Immutable collections - perhaps guava integration or optional extension module?


#1

Hi,

I’m wondering if there is some plans on integrating or to some extent replicating the google guava immutable collections.  Perhaps an optional ‘Immutable collections’ module would be a nice for those who want functionality similar to Guava’s immutable collections (and returned the Koltin read only List, Set etc).

  // using google guava collections - no extensions
  val immutableSet = ImmutableSet.of("red","green")
  immutableSet.add("blue") // compile still allows

Is there a recommended alternative to using java.util.Collections.unmodifiableSet() ?

  // kotlin.MutableList
  val mutList = arrayListOf("one")

  // returns a java.util.List / kotlin.MutableList
  val readOnlyList = Collections.unmodifiableList(mutList);
  readOnlyList.add("two") // allowed by compiler

  // but I can type it to a kotlin.List ...
  val readOnlyList2 : kotlin.List<String> = Collections.unmodifiableList(mutList);
  readOnlyList2.add("two") // does not compile

Cheers, Rob.


#2

I've just had another conversation on this and the general thoughts were:

> integrating or to some extent replicating the google guava immutable collections

Most cases are going to be satisfied by the existing functions listOf(), mapOf() etc.  The need for guava like immutable builders or greater immutable protection than already provided by the read only Kotlin List, Set, Map etc is very likely unwarranted.

> Is there a recommended alternative to using java.util.Collections.unmodifiableSet() ?

Just using the explicit read only Kotlin type is easy enough and does the job but there might be a better approach.
On MutableSet/MutableList there is the copyToArray() method so perhaps a similar copy() or unmodifiable() method would be a decent approach?

Thanks, Rob.


#3

toList()/toSet()/toMap() seem to be what you are looking for with the "copy" method


#4

There are plans for adding immutable/persistent collection classes in the future, but no concrete decisions are taken yet


#5

Right thanks.  Yes toSet() toList() does the trick - I just didn't find them.  

Looking at the implementation for toList() …

  public fun <T> Iterable<T>.toList(): List<T> {
  return toCollection(ArrayList<T>())
  }

… I wonder if the ImmutableArrayList implementation could be used instead of ArrayList so more like:

  public fun<T> MutableList<T>.toList() : List<T> {
  &nbsp;&nbsp;val array = this.copyToArray()
  &nbsp;&nbsp;return ImmutableArrayList(array, 0, array.size)

  }

but yes, toSet() toList() is all good - thanks !!!


#6

ImmutableArrayList is there for historical reasons only. We'll probably have it removed or reimplemented.