```val commands: MutableSet<Command<JDAComma...
# announcements
d
Copy code
val commands: MutableSet<Command<JDACommandSender>> = mutableSetOf()
get() = Collections.unmodifiableSet(field)
My goal is to allow the class itself to modify
commands
directly, but others to only be able to get an unmodifiable version of the contents. Is there any direct way to achieve this?
n
well, basically what you have there, but you'll likely need two fields -- one private mutable one and another public unmodifiable one that provides a custom get() like what you have. you might also ask yourself whether the public getter should return a defensive copy or not, otherwise it's possible the unmodifiable set will change out from under them
Copy code
private val privateCommands = mutableSetOf<Command>()
val commands get() = Collections.unmodifiableSet(privateCommands)
// or
val commands get() = Collections.unmodifiableSet(privateCommands.toSet())
or in another vein, you could use kotlinx persistent sets and just have a private setter for the whole field, e.g.
Copy code
val commands = persistentSetOf<Command>()
    private set
d
Hmm, could you explain what persistent sets are?
@nanodeath the persistent collection option provides an error with
private set
and
val
because val cannot be reassigned. Should it be
var
or should private set be removed?
n
sorry, yes, should be var
eh, it's kinda long to explain the persistent concept here, but basically mutations return a copy + the mutation. you can't actually modify the original collection. there are a lot of tricks done to make it more efficient than literally copying internal data around.
😮 1
d
All right, thank you 🙂