Immutable Collections Library for Kotlin

Kotlin Fest Reject Conference 2019

Sep. 9, 2019

Nagahori Shota

@nashcft

In the Keynote...

Immutable Collections Library for Kotlin

  • One of the kotlinx libraries
  • Provides "Immutable collection interfaces and implementation prototypes"
  • https://github.com/Kotlin/kotlinx.collections.immutable
  • Current version: 0.2
    • Maybe 0.3 will be released soon...?
    • 0.3 includes MPP support
  • ​"Will be part of the standard library in the future" (from keynote)

Collections in Standard Library Are Not Immutable

• Those interfaces gives read-only APIs, but their instances can be modified

• e.g. In Kotlin/JVM, the instances are actually Java collections in java.util

    • They can be casted into mutable collections

• Further reading: The Mystery of Mutable Kotlin Collections - ProAndroidDev

Collections in Standard Library Are Not Immutable

Collections in Standard Library Are Not Immutable

Collections in Standard Library Are Not Immutable

Interfaces

Two families of collections + collection builder:

  • Immutable collections
    • Read-only APIs, not modifiable implementations
  • Persistent collections
    • Immutable collections + modification operation APIs (e.g. set, add, removeAt)
  • Collection Builders
    • Builders to create new instances with specified mutation applied to the original collections

Interfaces: Immutable Collections

Interface Base Interface(s)
ImmutableCollection Collection
ImmutableList ImmutableCollection, List
ImmutableSet ImmutableCollection, Set
ImmutableMap Map

Interfaces: Persistent Collections

Interface Base Interface(s)
PersistentCollection ImmutableCollection
PersistentList PersistentCollection, ImmutableList
PersistentSet PersistentCollection, ImmutableSet
PersistentMap ImmutableMap

Interfaces: Collections Builders

Interface Base Interface(s)
PersistentCollection.Builder MutableCollection
PersistentList.Builder PersistentCollection.Builder, MutableList
PersistentSet.Builder PersistentCollection.Builder, MutableSet
PersistentMap.Builder MutableMap

Immutable + Modification Operation?

  • Modification functions return new instances to which the modification is applied
  • Efficient new instance creation by "structural sharing"
    • Shares common parts with the original instance
    • Returns the same instance if the applied operation did not actually modify it 

Implementations of Interfaces

Transformation Operations

🙏