Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use map elements as method arguments

Tags:

scala

I've been stuck on this for a while now: I have this method

Method(a: (A,B)*): Unit

and I have a map of type Map[A,B], is there a way to convert this map so that I can directly use it as an argument? Something like:

Method(map.convert)

Thank you.


1 Answers

You can build a sequence of pairs from a Map by using .toSeq.

You can also pass a sequence of type Seq[T] as varargs by "casting" it with : _*.

Chain the conversions to achieve what you want:

scala> val m = Map('a' -> 1, 'b' -> 2, 'z' -> 26)
m: scala.collection.immutable.Map[Char,Int] = Map(a -> 1, b -> 2, z -> 26)

scala> def foo[A,B](pairs : (A,B)*) = pairs.foreach(println)
foo: [A, B](pairs: (A, B)*)Unit

scala> foo(m.toSeq : _*)
(a,1)
(b,2)
(z,26)
like image 154
Philippe Avatar answered Aug 14 '26 23:08

Philippe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!