If I have Seq('a -> 1, 'b -> "some text")
, how can I call a function f(a: Int, b: String)
, filled with parameters from Seq
, bound by name (a, b)?
Asked
Active
Viewed 288 times
1

Krisztián Balla
- 19,223
- 13
- 68
- 84

andrey.ladniy
- 1,664
- 1
- 11
- 27
-
2Possible duplicate of http://stackoverflow.com/questions/20731069/unwrapping-a-list-or-map-as-function-arguments-in-scala – mattsilver Apr 28 '15 at 06:44
-
Seq may be Seq('a -> 1, 'b -> "some text"), or Seq('b -> "some text", 'a -> 1), so varargs and tupled are not approach. From post (how i understand): "However, there is no analogous Scala syntax." – andrey.ladniy Apr 28 '15 at 06:53
1 Answers
0
You should be able to do it using scala-reflect, I believe. Something like this (untested):
def applyWithNamedParameters[T: ClassTag](obj: T, m: MethodSymbol, params: Map[String, Any]) {
val methodMirror = scala.universe.runtime.currentMirror.reflect(obj).reflectMethod(m)
val paramNames = m.paramss.flatten.map(_.name.toString)
val paramValues = paramNames.map(params)
methodMirror.apply(paramValues)
}
params
are given as a map instead of Seq to simplify code a bit.

Alexey Romanov
- 167,066
- 35
- 309
- 487