If I have
val key1 = "mykey"
val key2 = 427
Is it possible to hash by both? I could do something like
val compoundKey = key1 + "#" + key2
myhash.put(compoundKey, value)
However that seems a bit clunky
Use a Tuple:
val compoundKey = (key1, key2)
I always prefer the new data type over Tuple for three reasons:
case class CompoundKey(key1: String, key2: String)
You have a name, especially in compiler warnings and an "expected CompoundKey" is clearer than a "expected Tuple2[String,String]". Or it just helps you with a type annotation to make your own code more readable, especially in nested structures like Maps
val k: CompoundKey = expensiveComputationOrNonObviousMethodCallsInARow(...)val keyMap: Map[CompoundKey,Key] instead of Map[(String,String),Key]
Access to the subkeys in CompoundKey can be done by name:
val ckey = CompoundKey("foo","bar")ckey.key1 instead of ckey._1
String, later on. That means if you change String to whatever that you doesn´t have to change Tuple2[String,String] all over your code. Only CompoundKey has to be adapted.(I even would use a wrapper case class Key(str: String) for the key class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With