Marko Mitic
07/22/2019, 11:42 AMprivate fun <E> Set<E>.immutable(): Set<E> = if (this is MutableSet) this.toSet() else thiskralli
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 AMsetMarko Mitic
07/22/2019, 11:57 AMval _set = setOf("")
_set.immutable() === _set //false
_set.toSet() === _set //falsekarelpeeters
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)