vendredi 17 avril 2015

scala: type equality of two variables

I have two Map[String, T]s, where T is an instance of subtype of Fruit. I need to construct new Map from two Maps, where the key is the common key names from the two maps, and the value is the Seq[Fruit] iff the values from the two maps shares the same type.



class Fruit

case class Apple() extends Fruit
case class Banana(num: Int) extends Fruit
case class Orange() extends Fruit


For example, if I have following two maps:



val map1 = Map("first" -> Apple(),
"second" -> Banana(3),
"third" -> Orange())

val map2 = Map("first" -> Orange(),
"second" -> Banana(4),
"third" -> Orange())


I need the result map, map3 which has following members:



generateMap(map1: Map[String, Fruit], map2: Map[String, Fruit]): Map[String, Seq[Fruit]]

=> results a map look like

Map("second" -> Seq(Banada(3), Banada(4)),
"third" -> Seq(Orange(), Orange())


I'm not sure how to write a function, generateMap. Could anyone help me to implement that? (using Scala 2.11.x)


Note that the class definitions (Fruits and others) are fixed, so I cannot modify them.






Aucun commentaire:

Enregistrer un commentaire