Foo 不带参数在 Scala 中编译错误?

Foo does not take parameters compile error in Scala?

编译出错,没看懂

case class Point(x: Int, y: Int)

trait Rectangular {

  def topLeft: Point
  def bottomRight: Point

  def left = topLeft().x //Compile error occurring here
  def right = bottomRight.x
  def width = right - left

  // any many more concrete geometric methods.
 }

我在定义第三个方法的那一行遇到编译错误,说 "Point does not take parameters"。

但我认为无论有无 (),您都可以调用不带参数的函数。由于 topLeft 只是一个没有参数且 return 类型为 Point 的方法。

区别在 Scala 文档中有描述:

http://docs.scala-lang.org/style/method-invocation.html

简而言之,括号用于标记具有副作用的方法,因此不允许调用 0-arity (标记为) 纯方法作为副作用。也可以看看: What is the rule for parenthesis in Scala method invocation?

它也与 UAP(统一访问原则)有关,因为没有 () 的方法被解释为访问器,因此您可以将其实现为 val:

trait A { def a: Int } //for some reason it works with parenthesis as well
class B extends A { val a: Int = 5 }

所以这里 someBInstance.a vs someATypedInstance.a 优于 someBInstance.a vs someATypedInstance.a()

除此之外,还有一个示例解释了为什么您不能将 def f = ...() 一起使用 - 仅仅是因为 () 也用作调用 [=21= 的快捷方式]:

scala> class Z { def apply() = 5 }
defined class Z

scala> def f = new Z
f: Z

scala> f()
res87: Int = 5