我有以下Scala代码:
sqlite3
对于它,我收到了这个错误:
references
知道造成这种情况的原因是什么?
答案 0 :(得分:4)
您传递给foreach
的参数是执行代码块(Unit
)的结果,而不是函数。
删除外括号(它们并没有真正伤害任何东西,但是不必要并且看起来很丑陋),并在开头添加_ =>
:
(0 to t).foreach { _ =>
...
println(getBestSolution(sumList))
}
这是创建未命名函数的正确语法。 =>
之前的内容是函数接受的参数列表。在您的情况下,您可以在其中放置下划线,因为您不需要参数的值。或者,如果您需要对其进行操作,可以给它命名,例如:(0 to t).foreach { x => println(x*x) }
答案 1 :(得分:1)
您也可以使用简单的for
理解来代替foreach
for(x <- 0 to t){
val n = readInt()
val a = readLine().split(" ").map(_.toInt).toList
val sumList = a.scanLeft(0)(_ + _).tail.toList
//println(classOf[sumList])
println(sumList)
println(getBestSolution(sumList))
}
总而言之,Programming in Scala本书指出Scala provides the for comprehension, which provides syntactically pleasing nesting of map, flatMap, and filter ... The for comprehension is not a looping construct, but is a syntactic construct the compiler reduces to map, flatMap, and filter.