尽管使用显式类型进行定义,但 Scala 正在推断 Nothing
scala is inferring Nothing though defining with explicit types
在以下代码中出现错误
Error:(48, 11) type mismatch;
found : (Int, Map[Int,Option[List[Int]]])
required: (Int, Nothing)
f
def tuplesWithRestrictions1(): (Int, Map[Int, Option[List[Int]]]) = {
val df = new DecimalFormat("#")
df.setMaximumFractionDigits(0)
val result = ((0 until 1000) foldLeft ((0, Map.empty(Int, Some(List.empty[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(log(x)) - 1
val v1 = (pow(10, v)).toInt
val m = (r._2).get(v1) {
case None => r._2 + (v1 -> List(x))
case Some(xs: List[Int]) => r._2 updated(x, xs :+ x)
}
val f = (r._1 + 1, m)
f
} else r
}
}
result
}
尽管我明确指定结果是 (Int, Map[Int, Option[List[Int]]]) 类型,但为什么编译器没有推断出任何结果?以及如何解决这个问题。
你的 val m = (r._2).get(v1)
returns Option[Option[List[Int]]]
。我认为,你应该在模式匹配中进行模式匹配以获得你想要的结果。
在以下代码中出现错误
Error:(48, 11) type mismatch;
found : (Int, Map[Int,Option[List[Int]]])
required: (Int, Nothing)
f
def tuplesWithRestrictions1(): (Int, Map[Int, Option[List[Int]]]) = {
val df = new DecimalFormat("#")
df.setMaximumFractionDigits(0)
val result = ((0 until 1000) foldLeft ((0, Map.empty(Int, Some(List.empty[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(log(x)) - 1
val v1 = (pow(10, v)).toInt
val m = (r._2).get(v1) {
case None => r._2 + (v1 -> List(x))
case Some(xs: List[Int]) => r._2 updated(x, xs :+ x)
}
val f = (r._1 + 1, m)
f
} else r
}
}
result
}
尽管我明确指定结果是 (Int, Map[Int, Option[List[Int]]]) 类型,但为什么编译器没有推断出任何结果?以及如何解决这个问题。
你的 val m = (r._2).get(v1)
returns Option[Option[List[Int]]]
。我认为,你应该在模式匹配中进行模式匹配以获得你想要的结果。