我读过如果方法不带参数且没有副作用,可以删除括号以提高可读性(斯巴达实现)。所以我可以调用以下代码
def withoutP = {
println(s"without p")
}
withoutP
然后我发现这个代码接受了参数,但我仍然可以在没有括号的情况下调用它。怎么样?
def isEven(n: Int) = (n % 2) == 0
List(1, 2, 3, 4) filter isEven foreach println
我尝试运行此代码,但它无效。为什么呢?
def withP(i:Int) = {
println("with p")
}
withP 1
';' expected but integer literal found.
[error] withP 1
[error] ^
[error] one error found
答案 0 :(得分:2)
在你的例子中
def isEven(n: Int) = (n % 2) == 0
List(1, 2, 3, 4) filter isEven foreach println
您实际上并未致电isEven
。您拨打filter
这是List
上的方法,而isEven
是filter
的参数。 filter
使用值作为参数,为列表中的每个值调用isEven
。
filter
写在infix notation中,这对于只接受一个参数的方法是合法的。替代方案是
List(1, 2, 3, 4).filter(isEven)
在这种情况下,.
也是必需的,因为filter
是List
类中的方法。
答案 1 :(得分:1)
1.对于第一个例子,不带参数调用withoutP
,这个编译由Scala允许省略arity-0 (no arguments)
2.对于第二个示例,使用参数调用withoutP 1
,这不是编译是由Infix notation需要以对象开始。所以你可以通过以下方式获得括号:
this withP 1 //infix notation with this (current object)
因此,对于1
和2
,省略括号规则并不相同。第一个是arity-0
规则,第二个应该使用Infix notation
来省略括号。