Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通用映射上的Scala模式匹配_Scala_Generics - Fatal编程技术网

通用映射上的Scala模式匹配

通用映射上的Scala模式匹配,scala,generics,Scala,Generics,在Scala中进行模式匹配时,处理泛型和擦除的最佳方法是什么。我正在寻找一个没有编译器警告的正确实现。我有一个函数,我想从中返回Map[Int,Seq[String]]。当前代码如下所示: def teams: Map[Int, Seq[String]] = { val dateam = new scala.collection.mutable.HashMap[Int, Seq[String]] // data.attributes is Map[String, Object]

在Scala中进行模式匹配时,处理泛型和擦除的最佳方法是什么。我正在寻找一个没有编译器警告的正确实现。我有一个函数,我想从中返回Map[Int,Seq[String]]。当前代码如下所示:

def teams: Map[Int, Seq[String]] = {
    val dateam = new scala.collection.mutable.HashMap[Int, Seq[String]]

    // data.attributes is Map[String, Object] returned from JSON parsing (jackson-module-scala)
    val teamz = data.attributes.get("team_players")
    if (teamz.isDefined) {
      val x = teamz.get
      try {
        x match {
          case m: mutable.Map[_, _] => {
            m.foreach( kv => {
              kv._1 match {
                case teamId: String => {
                  kv._2 match {
                    case team: Seq[_] => {
                      val tid: Int = teamId.toInt
                      dateam.put(tid, team.map(s => s.toString))
                    }
                  }
                }
              }
            })
          }
        }
      } catch {
        case e: Exception => {
          logger.error("Unable to convert the team_players (%s) attribute.".format(x), e)
        }
      }

      dateam
    } else {
      logger.warn("Missing team_players attribute in: %s".format(data.attributes))
    }
    dateam.toMap
}

使用
进行理解是合理的(使用一些内置模式匹配)。我们还可以考虑,
Map
是一个元组列表,在我们的
(String,Object)
类型中。此外,在本例中,我们将忽略可能的例外情况,因此:

import scala.collection.mutable.HashMap

def convert(json: Map[String, Object]): HashMap[Int, Seq[String]] = {

  val converted = for {
    (id: String, description: Seq[Any]) <- json
  } yield (id.toInt, description.map(_.toString))

  HashMap[Int, Seq[String]](converted.toSeq: _*)
}
导入scala.collection.mutable.HashMap
def convert(json:Map[String,Object]):HashMap[Int,Seq[String]={
val转换=用于{

(id:String,description:Seq[Any])使用Scala库来处理它。有一些基于Jackson的库(例如Play的——请参见独立使用),还有一些库不是基于Jackson的库(我更喜欢的库,不过你也可以选择)


这些库和其他库解决了这个问题。手工操作很笨拙,而且容易出错,所以不要这样做。

请添加此代码生成的编译器警告。.这里需要大量上下文--首先,你到底想完成什么?你只是“模式匹配”有一个例子,所以意图并不清楚。你得到了什么错误,输入了什么?我有一些JSON数据,我知道是Map[Int,Seq[String]]。不幸的是,从Jackson库中我得到了Map[String,Object],所以我在寻找某种类型的转换:)