Surender Raja - 2 months ago 5x
Scala Question

# How to return a Map with Value Type as String in scala

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

◾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]

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)
}