Scala string pattern matching by multiple possible groups -
given input map[string,string]
such
val in = map("name1" -> "description1", "name2.name22" -> "description 22", "name3.name33.name333" -> "description 333")
what simple way extract each name , each description , feed them 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
you can use 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 *
parameters must come last in function signature (otherwise compiler won't able decide stop).
from 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
Comments
Post a Comment