Question on trait

I have following code:

class Point(val x: Int, val y: Int) {}
trait Rectangular {
def topLeft: Point
def bottomRight: Point
def left = topLeft.x
def right = bottomRight.x
def width = right - left
}
class Rectangle(val topLeft: Point, val bottomRight: Point)
extends Rectangular {
// other methods…
}
val rect = new Rectangle(new Point(1, 1), new Point(10, 10))
println(rect.left)

It prints 1.
I haven’t implemented topLeft. So how does it work?

You have defined two fields by this code. In Scala, abstract method can be implemented through field with identical name. In other words, you have implemented

1 Like

In other words, there is a definition of matching members which says members with the same name and types that align somehow are matching for purposes of defining or overriding that member.

Since you brought it up, I understand the difference between val, def, and lazy val, but I wonder why I have to distinguish these details about the implementation of a computation in 2018. Is there any research ongoing to make these details of the back end? I realize 2018 doesn’t feel very cutting edge, but when 2020 comes around, we’re definitely going to be saying, But it’s 2020! about everything.

I’d argue, the reason why you have to distinguish these is, that Scala allows for side effects. With pure code, the difference is merely performance-wise, but as soon as there is some side effect happening in your def, val or lazy val, the difference becomes semantic.

So I guess as long as side effects are allowed, all variants will stay in the language, even if the compiler could detect the absence of side effects and optimize accordingly.

1 Like