带有选项/一些的 scala 地图给出匹配错误



以下代码产生运行时错误,如下所示。可能引起以下错误的原因。请解释一下。

线程"主"scala 中的异常。MatchError: Some(Some(List(17((( (of class scala.一些( at com.discrete.CountingSupp$.$anonfun$tuplesWithLimits1$1(CountingSupp.scala:43(

def tuplesWithRestrictions1(): (Int, Map[Int, Option[List[Int]]]) = {
val df = new DecimalFormat("#")
df.setMaximumFractionDigits(0)
val result = ((0 until 1000) foldLeft[(Int, Map[Int, Option[List[Int]]])] ((0, Map.empty[Int, Option[List[Int]]]))) {
(r: (Int, Map[Int, Option[List[Int]]]), x: Int) => {
val str = df.format(x).toCharArray
if (str.contains('7')) {
import scala.math._
val v = floor(log10(x)) - 1
val v1 = (pow(10, v)).toInt
val m: Map[Int, Option[List[Int]]] = (r._2).get(v1) match {
case None => r._2 + (v1 -> Some(List(x)))
case Some(xs: List[Int]) => r._2 updated(x, Some(x::xs))
}
val f = (r._1 + 1, m)
f
} else r
}
}
result
}

地图上.get的返回类型是

get(k: K): Option[V]

斯卡拉文档

/** Optionally returns the value associated with a key.
*
*  @param  key    the key value
*  @return an option value containing the value associated with `key` in this map,
*          or `None` if none exists.
*/
def get(key: K): Option[V]

现在

r._2.get(v1)返回"值"选项。因此,最终的返回类型将是Option[Option[List[Int]]]

您正在尝试Option[T]进行模式匹配,但实际值类型是Option[Option[Int]],该类型未在匹配中捕获。

  1. 使用r._2(v1)提取值并匹配。在映射中找不到v1时引发异常。

  2. 在提供默认值map内部匹配。

    r._2.get(k1).map {
    case None => r._2 + (v1 -> Some(List(x)))
    case Some(value) => r._2 updated(x, Some(x::xs))
    }.getOrElse(defaultValue)
    
def tuplesWithRestrictions1(): (Int, Map[Int, List[Int]]) = {
val df = new DecimalFormat("#")
df.setMaximumFractionDigits(0)
val result = ((0 until 1000) foldLeft[(Int, Map[Int, List[Int]])] ((0, Map.empty[Int, List[Int]]))) {
(r: (Int, Map[Int, List[Int]]), x: Int) => {
val str = df.format(x).toCharArray
if (str.contains('7')) {
import scala.math._
val v = floor(log10(x))
val v1 = (pow(10, v)).toInt
val m: Map[Int, List[Int]] = (r._2).get(v1) match {
case Some(xs: List[Int]) => r._2 updated(v1, x :: xs)
case None => r._2 + (v1 -> List(x))
}
val f = (r._1 + 1, m)
f
} else r
}
}
result
}

最新更新