What would be the idiomatic/semantic way to define...
# random
o
What would be the idiomatic/semantic way to define a limited size length of a collection? Given a
data class ChatConversation
, where a chat conversation is always between two users (userId), which type would fit the most? I was thinking about a
val userIds: Set<Int>
but that doesn't enforce the min 2, max 2. Also thought about a
val userIds: Pair<Int, Int>
, but the fact that
Pair(1, 2) == Pair(2, 1)
equals to false makes it a inproper fit given the case here, since a conversation between Bob and Alice should be considered the same as a conversation between Alice and Bob. EDIT: Possible option:
Copy code
data class TwoSizedSet<T>(val value: Set<T>) {
    init {
        require(value.size == 2)
    }
}
c
Why use a collection at all? Seems ill-fitted if you know the size ahead of time.
o
Because it makes querying easier and more semantic I think?
When I query my repository
where userA = 1 and userB = 2
, it forces me to check on both sides (no difference between a conversation of Bob and Alice, and Alice and Bob)
c
Trying to understand why prefer a collection over
data class TwoSize<T>(val first: T, val second: T)
o
Wouldn't that be the same as a
Pair<T>
?
c
although the
equal
semantic of the class I just wrote will be similar to
Pair
so you probably don’t want that
hehe you beat me to it 🙂
If you absolutely want a collection but ordering matters,
Set
is definitely not the right choice though 🙂
o
Why would ordering matter in this case?
c
That was your own requirement:
the fact that
Pair(1, 2) == Pair(2, 1)
equals to false makes it a inproper fit given the case here, since a conversation between Bob and Alice should be considered the same as a conversation between Alice and Bob.
o
I thought ordering does not matter, that's why I thought of a Set
Perhaps there is a misunderstanding in my wording there. I'm basically saying that I wanted that
Pair(1, 2) == Pair(2, 1)
equals to true, which isn't the case. That makes the requirement unordered, instead of ordered. Right?
Conversation between Bob and Alice is the same as a conversation between Alice and Bob, which is not what the Pair does.
c
Never mind
Ignore what I wrote
Deleting it
o
It's a tricky one, isn't it😁.