为什么下面的方法()在等效函数返回布尔值(如预期)时返回单位值(即)?
// aMethod(1) returns ()
def aMethod(a: Int) { true }
// aFunction(1) returns true
val aFunction = (a: Int) => true
Run Code Online (Sandbox Code Playgroud)
为了清楚起见,我将添加此内容:
def aMethod(a: Int) {
true
}
Run Code Online (Sandbox Code Playgroud)
这回来了Unit.
def aMethod(a: Int) = {
true
}
Run Code Online (Sandbox Code Playgroud)
这回来了Boolean.(由编译器推断)
关键是,你必须有一个=你的方法的签名后,使其返回的东西比不同Unit.如果有a =,则返回类型将由编译器推断,具体取决于方法体中的最后一个表达式.
让我们Boolean为你的方法添加一个显式的返回类型:
def aMethod(a: Int): Boolean
{
return true
}
Run Code Online (Sandbox Code Playgroud)
现在我们有一个编译器错误:
Error:(120, 5) illegal start of declaration (possible cause: missing `=' in front of current method body)
return true
^
Run Code Online (Sandbox Code Playgroud)
糟糕,让我们尝试做它所说的:
def aMethod(a: Int): Boolean =
{
return true
}
Run Code Online (Sandbox Code Playgroud)
现在我们的方法返回Boolean而不是Unit.
所以你的问题是滥用return和不恰当的方法语法.如果=在方法声明中没有a ,则假定返回类型为Unit.
让我们的代码更整洁:
object X {
def aMethod(a: Int) = true
val aFunction = (a: Int) => true
def test(f: Int => Any) = (1 to 5) map f foreach println
}
Run Code Online (Sandbox Code Playgroud)
我删除了return- 我在SO上写了另一个答案,为什么你不应该使用它.我删除了多余的花括号.
我也把你的for循环变成了更像Scala的理解.