Would this work? `private fun <E> Set<E&g...
# getting-started
m
Would this work?
private fun <E> Set<E>.immutable(): Set<E> = if (this is MutableSet) this.toSet() else this
k
Yes, it does. Thanks to a special intrinsic by the compiler, it is possible to check on the mutability of a set.
Take a look at this little test:
Copy code
val mutableSet = mutableSetOf("")
val immutableSet = mutableSet.immutable()

mutableSet.add("Hello")

println(immutableSet)
It prints
[]
d
In theory, yes. But afaik there are no implementations in the stdlib that only implement
set
m
issue is that it works identically to toSet() 🙂
Copy code
val _set = setOf("")
_set.immutable() === _set //false
_set.toSet() === _set     //false
k
In other words it "works", but you'll just get back another set that
is MutableSet
.
m
because all sets are actually implemented as mutable sets (excepts singleton ones, I think)
a
Well, yes and no. toSet just return a new copy of set, not necessary immutable one (you can check
is MutableSet
again) You can use https://github.com/Kotlin/kotlinx.collections.immutable for this purposes (if you need to really achieve immutability) If you just want to be sure that your original set will not be changed in other code, you can use your current code (but it's better to be renamed in that case)
âž• 2