我有以下Scala代码:
object Solution {
def getBestSolution(sumList: List[Int]): Int = {
return 0
}
def main(args: Array[String]) {
val t = readInt()
(0 until t).foreach({
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))
})
}
}因此,我得到了一个错误:
file.scala:16: error: type mismatch;
found : Unit
required: Int => ?
println(getBestSolution(sumList))
^
one error found知道是什么原因造成的吗?
发布于 2017-06-14 17:11:19
要传递给foreach的参数是执行代码块(这是Unit)的结果,而不是函数。去掉括号外的括号(它们并不真正伤害任何东西,但没有必要,而且看起来很难看),并在开头添加_ =>:
(0 to t).foreach { _ =>
...
println(getBestSolution(sumList))
}这是创建未命名函数的正确语法。=>之前的内容是函数接受的参数列表。在您的例子中,您可以在那里放置一个下划线,因为您不需要参数的值。或者你可以给它起一个名字,如果你需要用它做一些事情,例如:(0 to t).foreach { x => println(x*x) }
发布于 2017-06-14 17:21:31
你也可以用简单的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))
}总之,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.
https://stackoverflow.com/questions/44550736
复制相似问题