I have a function that takes a `String` `Int` and ...
# getting-started
d
I have a function that takes a
String
Int
and a data class, how can I make a unique hash key out of all three (for a key in a cache map) without any extra allocations? (I know I could always put them all in a data class and use that as a key or just use it's hashCode()... but I don't need that extra class...)
s
“Without any extra allocations” probably means writing (or having the IDE generate) a custom implementation. But if you’re on JVM and don’t mind allocating an array, you could use
Objects.hash(…)
, which takes a vararg.
This answer probably isn’t useful, since for a map key you need a full equality check, not just a hashCode
d
I don't mind a custom implementation... but I am on the jvm...
s
For your use case, sounds like you could also use a `Triple`… not that I would normally recommend those 😅
d
This answer probably isn’t useful, since for a map key you need a full equality check, not just a hashCode
It's just a cache layer over an api to avoid requesting the same response for the same input params... so I don't really care of the content of the key, just that there shouldn't be any collisions, and effieciency of retreival.
not that I would normally recommend those
So what would you recommend?
s
Normally I try to avoid using
Triple
because you lose the ability to give names to the three values. I would usually just go ahead and make a data class, even if the use case seems trivial.
d
Anyways `Triple`s hashCode() algo might not be optimized for what it contains as much as a data class is? (I guess same would apply for Objects.hash...)
s
Actually I think
Triple
is currently implemented as a data class, so the hashCode behaviour is probably identical.
d
Yeah, but doesn't the compiler use the param types at compile time to make a better implementation of hashCode() (than Triple) for official data classes?
s
🤔 maybe there would be a difference if one or more of the properties is a primitive type… not sure
m
Primitive types in a Triple will automatically get boxed, so a custom data type should be more efficient.
👍 2
😮 1