Foo在Scala中没有参数编译错误?

时间:2015-12-28 13:02:03

标签: scala function methods traits

我有编译错误,我不明白。

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不接受参数"。

但我认为你可以调用一个不带{1}或不带()参数的函数。由于topLeft只是一个没有参数且返回类型为Point的方法。

1 个答案:

答案 0 :(得分:4)

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 = ...()一起使用 - 只是因为()也被用作调用apply的快捷方式}:

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

scala> def f = new Z
f: Z

scala> f()
res87: Int = 5