首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找股,必要的Int

查找股,必要的Int
EN

Stack Overflow用户
提问于 2017-06-14 17:02:57
回答 2查看 2.1K关注 0票数 0

我有以下Scala代码:

代码语言:javascript
复制
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)) 
        })
    }

}

因此,我得到了一个错误:

代码语言:javascript
复制
file.scala:16: error: type mismatch;
 found   : Unit
 required: Int => ?
            println(getBestSolution(sumList))
                   ^
one error found

知道是什么原因造成的吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-06-14 17:11:19

要传递给foreach的参数是执行代码块(这是Unit)的结果,而不是函数。去掉括号外的括号(它们并不真正伤害任何东西,但没有必要,而且看起来很难看),并在开头添加_ =>

代码语言:javascript
复制
(0 to t).foreach { _ => 
   ...
   println(getBestSolution(sumList))
}

这是创建未命名函数的正确语法。=>之前的内容是函数接受的参数列表。在您的例子中,您可以在那里放置一个下划线,因为您不需要参数的值。或者你可以给它起一个名字,如果你需要用它做一些事情,例如:(0 to t).foreach { x => println(x*x) }

票数 4
EN

Stack Overflow用户

发布于 2017-06-14 17:21:31

你也可以用简单的for理解来完成,而不是foreach

代码语言:javascript
复制
  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.

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44550736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档