https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dave08

01/30/2023, 4:40 PM
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

Sam

01/30/2023, 4:44 PM
“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

dave08

01/30/2023, 4:45 PM
I don't mind a custom implementation... but I am on the jvm...
s

Sam

01/30/2023, 4:46 PM
For your use case, sounds like you could also use a `Triple`… not that I would normally recommend those 😅
d

dave08

01/30/2023, 4:50 PM
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

Sam

01/30/2023, 4:51 PM
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

dave08

01/30/2023, 4:53 PM
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

Sam

01/30/2023, 4:55 PM
Actually I think
Triple
is currently implemented as a data class, so the hashCode behaviour is probably identical.
d

dave08

01/30/2023, 4:56 PM
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

Sam

01/30/2023, 4:59 PM
🤔 maybe there would be a difference if one or more of the properties is a primitive type… not sure
m

mkrussel

01/30/2023, 5:00 PM
Primitive types in a Triple will automatically get boxed, so a custom data type should be more efficient.
👍 2
😮 1
4 Views