I just noticed something interesting about Kotlin’s Set
data structure and its interaction with Java.
Consider a List
object first. If I have this code in Kotlin:
private val aList = listOf(1,2,3)
fun giveMeAList() = aList
fun printAList() = println(aList)
and this in Java:
List<Integer> aList = TestKotlin.INSTANCE.giveMeAList();
TestKotlin.INSTANCE.printAList(); // [1,2,3]
aList.add(4); // UnsupportedOperationException
TestKotlin.INSTANCE.printAList();
I get an UnsupportedOperationException
at the .add
. This is expected because under the hood it’s an (immutable) List
. But because it fulfills the List
interface and Java doesn’t have the concept of immutable collections, the compiler doesn’t detect this and it fails at runtime.
But now consider the identical Kotlin code, except replace List
with Set
types. Then this Java code:
Set<Integer> aSet = TestKotlin.INSTANCE.giveMeASet();
TestKotlin.INSTANCE.printASet(); // (1, 2, 3)
aSet.add(4); // no exception thrown
TestKotlin.INSTANCE.printASet(); // (1, 2, 3, 4)
No exception is thrown. Just like List
‘s, Kotlin differentiates between mutable and immutable Set
‘s. In Kotlin there is no aSet.add
. Why do sets not exhibit the same behavior? Is this intentional? Is this something that may not be changed under the hood in a future version of Kotlin?
3
Yes, this is something that may change under the hood.
In general, Kotlin tries not to reinvent data structure implementations for the JVM, instead preferring to use built-in java.util
data structures. For listOf
, it might make sense to use Arrays.asList
, which doesn’t support add
; for sets, there isn’t really anything better than LinkedHashSet
.
This is generally perfectly normal for Kotlin; it certainly doesn’t guarantee that its collections cannot be modified, it only guarantees that their public API available from the Kotlin language doesn’t support mutation.
Kotlin’s standard library doesn’t have the concept of immutable collection interfaces either. Set, List, and Map are read-only, not immutable. This means they can be read-only windows to mutable data.
If you want truly immutable collection interfaces, there is an official Kotlin library for that: https://github.com/Kotlin/kotlinx.collections.immutable
3