Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: return readonly Set/Collection

I want to return a readonly Set/Collection of a property. What is the best idiomatic way in Kotlin?

In Java we could use Collections.unmodifiableSet()

val property: MutableSet<String> = mutableSetOf()

    get() {
        // ?
    } 
like image 899
Dachstein Avatar asked Jan 26 '26 02:01

Dachstein


1 Answers

If you want to mutate the set from within the implementation of your class, you have no other way than to have two separate properties with different types.

private val mutableProperty: MutableSet<String> = mutableSetOf()

val property: Set<String> 
    get() = mutableProperty

With this approach, your interface exposes the set as a read-only type, but an explicit cast (or a usage from Java) will anyway allow to mutate the set. If you want to ensure that the set is not mutated from outside, you can wrap it into an unmodifiable set:

val property: Set<String>
    get() = Collections.unmodifiableSet(mutableProperty)

Optionally, make a defensive copy, so that the caller won't see the change to the mutable set, or use any efficient 3rd-party immutable collection implementation.

like image 186
hotkey Avatar answered Jan 28 '26 23:01

hotkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!