Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I represent a compound key in Scala?

Tags:

scala

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

like image 818
Hoa Avatar asked Oct 28 '11 05:10

Hoa


2 Answers

Use a Tuple:

val compoundKey = (key1, key2)
like image 61
Jean-Philippe Pellet Avatar answered Oct 28 '22 13:10

Jean-Philippe Pellet


I always prefer the new data type over Tuple for three reasons:

case class CompoundKey(key1: String, key2: String)
  1. 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]

  2. Access to the subkeys in CompoundKey can be done by name:

    val ckey = CompoundKey("foo","bar")
    ckey.key1 instead of ckey._1

  3. It lets you change your representation of the nested type, here 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)

like image 32
Peter Schmitz Avatar answered Oct 28 '22 14:10

Peter Schmitz