views:

275

answers:

1

I'm a Scala beginner and this piece of code makes me struggle.

Is there a way to do pattern matching to make sure everything i pass to Data is of the correct type? As you can see i have quite strange datatypes...

class Data (
val recipient: String, 
val templateText: String, 
val templateHtml: String, 
val blockMaps: Map[String,List[Map[String,String]]], 
templateMap: Map[String,String]
)

...

val dataParsed = JSON.parseFull(message)
dataParsed match {
 case dataParsed: Map[String, Any] => {
  def e(s: String) = dataParsed get s
  val templateText = e("template-text")
  val templateHtml = e("template-html")
  val recipient = e("email")
  val templateMap = e("data")
  val blockMaps = e("blkdata")

  val dependencies = new Data(recipient, templateText, templateHtml, blockMaps, templateMap)
  Core.inject ! dependencies
 }

...

+1  A: 

I guess your problem is you want to be able to patten match the map that you get from parseFull(), but Map doesn't have an unapply.

So you could pattern match every single value, providing a default if it is not of the correct type:

val templateText: Option[String] = e("template-text") match {
  case s: String => Some(s)
  case _ => None
}

Or temporarily put all the data into some structure that can be pattern matched:

val data = (e("template-text"), e("template-html"), e("email"), e("data"),
            e("blkdata"))

val dependencies: Option[Data] = data match {
  case (templateText: String,
        templateHtml: String,
        blockMaps: Map[String,List[Map[String,String]]],
        templateMap: Map[String,String]) =>
    Some(new Data(recipient, templateText, templateHtml, blockMaps, templateMap))
  case _ => None
}
Ben James
thank you for your answer but it actually does not work. I'm not sure i'm doing everything right but i get this error when compiling with ant, in both cases.error: pattern type is incompatible with expected type; [scalac] found : String [scalac] required: Option[Any] [scalac] case s: String => Some(s)stops to string, maps seems to be fine..
Federico
wrapping each value with Some solves the issue. case(Some(templateText: String), Some(...))thanks for the start tho
Federico