Pattern matching over a range of values ​​in scala

I'm starting a Scala newbie and this piece of code makes me fight.

Is there a way to do pattern matching to make sure that everything I pass to Data is of the correct type? As you can see, I have pretty strange data types ...

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
 }

...

+3
source share
1 answer

I think your problem is that you want to be able to map the map that you get from parseFull(), but Map does not have unapply.

Thus, you can match each individual value with a default value if it does not match the type:

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
}
+1

Source: https://habr.com/ru/post/1724050/


All Articles