princess of persia
princess of persia

Reputation: 2232

Scala Array of Maps

I am trying to convert an array of strings into an array of maps(string,string) by mapping each element into the array to (element,regex it matches). My code is as follows, however it throws me error when I run it.

var articles:Array[Map[String,String]] = rawArticles map(x => x, x match {
    case ArticleRE(id) => id
    case _ => " " 
}
)).toMap

rawArticles is the original array and ArticleRE is the regex I am matching.

Upvotes: 0

Views: 2938

Answers (2)

jroesch
jroesch

Reputation: 1260

It appears to me that your issue is trying to call toMap on something that isn't a Seq[(A, B)]. Assuming a trivial case like this (it compiles just fine in Scala 2.10 with a few changes):

val rawArticles = Array("articleOne", "articleTwo", "articleThree")
val articleRE = "(.*)".r
/* some place holder value for no match */
val noMatch = ""

val articles = rawArticles map { x => Map(
  x -> x match {
    case articleRE(id) => (id, articleRE.toString)
    case _             => ("", noMatch)
  })
}

I think your issue here was trying to convert a Seq that wasn't a Seq of Tuples, you can also directly use case in Map, as Map can take a PartialFunction.

Upvotes: 1

huynhjl
huynhjl

Reputation: 41646

If you are sure about the types that you want then this should work:

var articles = rawArticles.map(x => Map(x -> (x match {
  case ArticleRE(id) => id
  case _ => " "
})))  

Upvotes: 0

Related Questions