从scala函数返回的打印值

Omn*_*ent 4 scala intellij-idea

object TestClass {
  def main (args: Array[String]) {
    println("Hello World");
    val c = List (1,2,3,4,5,6,7,8,9,10)
    println(findMax(c))
  }
  def findMax (tempratures: List[Int]) {
    tempratures.foldLeft(Integer.MIN_VALUE) {Math.max}
  }
}
Run Code Online (Sandbox Code Playgroud)

显示的输出是

Hello World 
()
Run Code Online (Sandbox Code Playgroud)

为什么输出不是

Hello World
10
Run Code Online (Sandbox Code Playgroud)

我在IntelliJ中这样做

Pab*_*dez 10

这是最常见的scala拼写错误之一.

您错过了=方法的最后:

def findMax (tempratures: List[Int]) {
Run Code Online (Sandbox Code Playgroud)

应该读:

def findMax (tempratures: List[Int]) = {
Run Code Online (Sandbox Code Playgroud)

离开=意味着你的方法返回Unit(没有).

  • @Omnipresent:每个方法都返回一些东西,但没有`=`,返回类型总是`Unit`,即`()`.请记住,Scala被设计为函数式语言,并且在函数式编程中,几乎每个构造都返回值,即使是`if`:`val x = if b {ifVal} {elseVal}`. (4认同)

0__*_*0__ 7

因为您定义的findMax没有返回类型,所以返回类型是Unit().

def findMax (tempratures: List[Int]) { ... }
Run Code Online (Sandbox Code Playgroud)

又名

def findMax (tempratures: List[Int]) : Unit = { ... }
Run Code Online (Sandbox Code Playgroud)

你想要的

def findMax (tempratures: List[Int]) : Int = { ... }
Run Code Online (Sandbox Code Playgroud)

或者省略类型

def findMax (tempratures: List[Int]) = { ... }
Run Code Online (Sandbox Code Playgroud)