I want to provide a `WrappedSet` class delegating ...
# getting-started
j
I want to provide a
WrappedSet
class delegating to an internal
Set
. This allows me to provide all the features of a Set, and also provide additional methods without polluting the extension functions of the
Set
interface.
Copy code
data class WrappedSet(private val items: Set<Int>) : Set<Int> by items {
    fun someCustomMethod(): Unit {}
}
However, this simple test shows I broke the symmetric requirements of the `equals` method:
Copy code
val pureSet = setOf(1)
val wrappedSet = WrappedSet(setOf(1))

println(pureSet == wrappedSet) // true
println(wrappedSet == pureSet) // false
What are your recommandations here? Should I provide a custom equals implementation that allows
WrappedSet
to be compared to a
Set
interface?
y
Set's contract is that if you have equal elements you should be equal. Thus, override equals (and hashcode) to delegate to the underlying set too
j
Which means my
WrappedSet
will be considered equal to a
Set
, if they have the same elements, is that OK?
e
j
Alright then, thank you both 🙏
m
Maybe making it a data class is unnecessary? Storing the elements as a private set, but then also BEING that set is double logic?
Copy code
class WrappedSet(
    items: Set<Int>,
) : Set<Int> by items {
    override fun equals(other: Any?) = (this as Set<*>) == other

    override fun hashCode(): Int = (this as Set<*>).hashCode()
}
j
I didn't make it a data class in my code, only in this example, I honestly don't why and must admit it is not required 😅 I went with:
Copy code
class WrappedSet(private val items: Set<Int>) : Set<Int> by items {
    override fun equals(other: Any?) = items == other
    override fun hashCode(): Int = items.hashCode()
}