I currently have the following, which works, but I'm very new to Scala and I'm wondering if there's a better way to do it.
val utmcsr = """.*utmcsr=(.*)""".r
val utmcmd = """.*utmcmd=(.*)""".r
val utmccn = """.*utmccn=(.*)""".r
val utmctr = """.*utmctr=(.*)""".r
val utmz = "14002953.138298057.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
utmz.split("""\|""").map {
case utmcsr(s) => List("utmscr", s)
case utmcmd(s) => List("utmcmd", s)
case utmccn(s) => List("utmccn", s)
case utmctr(s) => List("utmctr", s)
case _ => ""
}.foldLeft(Map[String,String]()) {
(m, s) =>
val key = s.asInstanceOf[List[String]].head
val value = s.asInstanceOf[List[String]].tail.head
m + (key -> value)
}
}
My main questions are:
- Why do I need to parse s as an instance of List - shouldn't it already be a list?
- Is there a way to do this with tuples instead of lists?
- Is there a built-in way to do the list to map conversion?