Marko Mitic
07/22/2019, 11:42 AMprivate fun <E> Set<E>.immutable(): Set<E> = if (this is MutableSet) this.toSet() else this
kralli
07/22/2019, 11:51 AMkralli
07/22/2019, 11:52 AMval mutableSet = mutableSetOf("")
val immutableSet = mutableSet.immutable()
mutableSet.add("Hello")
println(immutableSet)
It prints []
diesieben07
07/22/2019, 11:52 AMset
Marko Mitic
07/22/2019, 11:57 AMval _set = setOf("")
_set.immutable() === _set //false
_set.toSet() === _set //false
karelpeeters
07/22/2019, 11:58 AMis MutableSet
.Marko Mitic
07/22/2019, 11:58 AMAlexander Levin
07/22/2019, 12:01 PMis 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)