Reputation: 20415
Given an input Map[String,String]
such as
val in = Map("name1" -> "description1",
"name2.name22" -> "description 22",
"name3.name33.name333" -> "description 333")
what is a simple way to extract each name and each description and feed them into a method such as
def process(description: String, name: String*): Unit = name match {
case Seq(n) => // find(n).set(description)
case Seq(n,m) => // find(n).find(m).set(description)
case Seq(n,m,o) => // find(n).find(m).find(o).set(description)
case _ => // possible error reporting
}
Many Thanks
Upvotes: 0
Views: 122
Reputation: 9168
You can do something like:
in foreach { case (ns, d) => process(d, ns.split("\\."): _*) }
Upvotes: 1
Reputation: 15783
You can use the splat operator _*
:
val in = Map("name1" -> "description1",
"name2.name22" -> "description 22",
"name3.name33.name333" -> "description 333")
def process(description: String, name: String*) = ???
in.map { x =>
process(x._2, x._1.split("\\."): _*)
}
Note that *
parameters must come last in the function signature (otherwise the compiler won't be able to decide where to stop).
From the REPL:
scala> def process(description: String, name: String*) = {
| name.foreach(println)
| println(description)
| }
process: (description: String, name: String*)Unit
scala> in.map { x =>
| process(x._2, x._1.split("\\."): _*)
| }
name1
description1
name2
name22
description 22
name3
name33
name333
description 333
Upvotes: 2