0

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

4
  • I guess you mean def process(tuple: (String, String)*) or def process(description: String, name: String), as either you can to process each entry one by one, or process all entries at once (which mean more than one 1 description). Commented Aug 18, 2014 at 10:14
  • @applicius one map entry at a time, keys arrayed. Commented Aug 18, 2014 at 10:15
  • What's the return type? Commented Aug 18, 2014 at 10:22
  • @applicius note update in question :) Commented Aug 18, 2014 at 10:23

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

You can do something like:

in foreach { case (ns, d) => process(d, ns.split("\\."): _*) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.