Maik Klein
Maik Klein

Reputation: 16148

Scala - Abstract functions in traits

trait Rectangular{
def topLeft:Point
def bottomRight:Point
def left=topLeft.x
def right=bottomRight.x
def width=right-left
//andmanymoregeometricmethods...
}


class Rectangle(val topLeft:Point,val bottomRight:Point)
extends Rectangular{
//othermethods...
}

In Rectangular he defines an abstract function and he implements it in class Rectangle with a val in the primary constructor.

Is this a special case in traits? Is this expected behavior?

Previously he describes that only def's can override def's. But in this case a val implements an abstract function, which is really strange.

Upvotes: 0

Views: 287

Answers (2)

Dan Simon
Dan Simon

Reputation: 13137

a val is actually syntactic sugar for defining a private variable and a public getter method with the same name, so a val basically includes a def. When you override a def with a val, the compiler uses the getter method as the function that overrides the def. You can also override a def with a var, which defines both a getter and a setter method (though I generally wouldn't consider such behavior "good" code).

Using def do define abstract properties allows the implementor to choose whether they want to use val, var, or def.

So, if the author claims that only def can override def, that is incorrect (perhaps it was the case in an early version of Scala?).

Upvotes: 3

paradigmatic
paradigmatic

Reputation: 40461

Unfortunately I never read that bok (shame on me). But this is wrong. You can override a def with a val or a lazy val. This pattern is very common.

To avoid weird behavior, it is highly recommended to avoid abstract val.

Upvotes: 1

Related Questions