scala中一系列值的模式匹配

时间:2009-11-26 23:49:14

标签: scala pattern-matching

我是Scala的初学者,这段代码让我很难过。

有没有办法进行模式匹配,以确保我传递给Data的所有内容都是正确的类型?如你所见,我有非常奇怪的数据类型......

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 个答案:

答案 0 :(得分:1)

我想您的问题是,您希望能够匹配从parseFull()获得的地图,但地图没有unapply

因此,您可以对每个值进行模式匹配,如果类型不正确,则提供默认值:

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

或者暂时将所有数据放入一些可以模式匹配的结构中:

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
}