Surender Raja - 1 year ago 95
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

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

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)
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download