Reputation: 3599
object passingmapstomethod {
def main(args:Array[String])={
val custs = Map(100->"surender",101->"raja")
val txns = Map(100->"USA", 101->"UK")
println(join(custs,txns))
}
def join[K,A,B,C](custs:Map[K,A],txns:Map[K,B]) :Map[K, C]=
{
for((k,va) <- custs; vb <- txns.get(k)) yield k -> va.toString()+"|"+ vb.toString()
}
}
Expected Output is
Map(101 -> raja|UK , 100 -> surender|USA)
But while running this I get error as
◾Implicit conversion found: ⇒ any2stringadd(): any2stringadd[(K, String)]
◾type mismatch; found : scala.collection.mutable.Iterable[String] required: scala.collection.mutable.Map[K,C]
◾Implicit conversion found: ⇒ option2Iterable(): Iterable[String]
◾Implicit conversion found: ⇒ ArrowAssoc(): ArrowAssoc[K]
Upvotes: 1
Views: 280
Reputation: 27692
You have three options:
(A) Remove the parametric type C from join as your return value will be always String
:
def join[K,A,B](custs:Map[K,A],txns:Map[K,B]) :Map[K, String]= {
for((k,va) <- custs; vb <- txns.get(k)) yield k -> va.toString()+"|"+ vb.toString()
}
(B) Add a generic combiner function and keep the method parametric:
def join[K,A,B, C](custs:Map[K,A],txns:Map[K,B], combiner: (A, B) => C) :Map[K, C]= {
for((k,va) <- custs; vb <- txns.get(k)) yield k -> combiner(va, vb)
}
(C) Always return a tuple, thus removing the parametric type C
too; and use mapValues
over its result in order to combine the tuple elements:
def join[K,A,B](custs:Map[K,A],txns:Map[K,B]) :Map[K, C]= {
for((k,va) <- custs; vb <- txns.get(k)) yield k -> (va, vb)
}
Upvotes: 3