Dachstein
Dachstein

Reputation: 4282

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() {
        // ?
    } 

Upvotes: 3

Views: 854

Answers (1)

hotkey
hotkey

Reputation: 148129

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.

Upvotes: 3

Related Questions