简体   繁体   English

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

[英]Foo does not take parameters compile error in Scala?

I have a compile error and I do not understand it. 我有一个编译错误,我不明白。

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.
 }

I am getting a compile error on the line where the third method is defined, saying "Point does not take parameters". 我在定义第三个方法的行上遇到编译错误,说“Point不接受参数”。

But I thought that you can invoke a function that does not take parameters with or without the () . 但我认为你可以调用一个不带参数的函数,有或没有() As topLeft is just a method that has no parameters and has a return type of Point . 由于topLeft只是一个没有参数且返回类型为Point

The difference is described in Scala documentation: Scala文档中描述了不同之处:

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

Shortly, parenthesis is used to mark a method that has side-effects, so it's not allowed to call 0-arity (marked as) pure-method as side-effectful. 简而言之,括号用于标记具有副作用的方法,因此不允许将0-arity(标记为)纯方法称为副作用。 See also: What is the rule for parenthesis in Scala method invocation? 另请参阅: Scala方法调用中的括号规则是什么?

It's also related to UAP (Uniform Access Principle) as method without () is interpreted as accessor, so you can implement it as a val : 它也与UAP(统一访问原则)有关,因为没有()方法被解释为访问器,因此您可以将其实现为val

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

So here someBInstance.a vs someATypedInstance.a is better than someBInstance.a vs someATypedInstance.a() 所以这里someBInstance.a vs someATypedInstance.a优于someBInstance.a vs someATypedInstance.a()

Besides that, there is an example that explains why you can't use def f = ... with () - simply because () is also used as shortcut to call apply : 除此之外,有一个例子可以解释为什么你不能使用def f = ... with () - 只是因为()也被用作调用apply快捷方式:

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

scala> def f = new Z
f: Z

scala> f()
res87: Int = 5    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM