https://kotlinlang.org logo
#random
Title
o

Orhan Tozan

03/23/2020, 12:12 PM
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

cedric

03/23/2020, 5:08 PM
Why use a collection at all? Seems ill-fitted if you know the size ahead of time.
o

Orhan Tozan

03/23/2020, 5:10 PM
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

cedric

03/23/2020, 5:13 PM
Trying to understand why prefer a collection over
data class TwoSize<T>(val first: T, val second: T)
o

Orhan Tozan

03/23/2020, 5:14 PM
Wouldn't that be the same as a
Pair<T>
?
c

cedric

03/23/2020, 5:14 PM
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

Orhan Tozan

03/23/2020, 5:15 PM
Why would ordering matter in this case?
I thought ordering does not matter, that's why I thought of a Set
c

cedric

03/23/2020, 5:15 PM
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

Orhan Tozan

03/23/2020, 5:18 PM
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

cedric

03/23/2020, 5:20 PM
Never mind
Ignore what I wrote
Deleting it
o

Orhan Tozan

03/23/2020, 5:21 PM
It's a tricky one, isn't it😁.
2 Views