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".
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
.
The difference is described in Scala documentation:
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. See also: What is the rule for parenthesis in Scala method invocation?
It's also related to UAP (Uniform Access Principle) as method without ()
is interpreted as accessor, so you can implement it as a 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()
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
:
scala> class Z { def apply() = 5 }
defined class Z
scala> def f = new Z
f: Z
scala> f()
res87: Int = 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With