Reputation: 1385
Consider following example:
abstract class Item {
def price: Double
def description: String
}
class SimpleItem1(override val price: Double, override val description: String) extends Item{}
class SimpleItem2(val price: Double, val description: String) extends Item{}
It compiles successfully and both extended classes have same methods. Are they actually the same? If not - what is the difference? If yes - please explain this to me a little bit, for example: why they decided that 'override' is optional here?
Upvotes: 3
Views: 3936
Reputation: 67290
Because price
and description
are abstract in Item
, you are not required to use the override
modifier. If they had default implementation, you would have to add the override
modifier.
Thus, in SimpleItem1
, the modifier is superfluous. There are some circumstances where adding an override
"just in case" makes sense. For example if you define a trait that you might want to mix-in to a class that has a default implementation.
Here is an example, where override
would make a difference:
trait Item0 {
def price: Int
}
trait Item1 extends Item0 {
def price = 33
}
trait Item2 extends Item0 {
override def price = 33
}
object Foo1 extends Item1 // ok
object Foo2 extends Item2 // ok
object Foo3 extends Item0 with Item1 // ok
object Foo4 extends Item2 with Item1 // NOPE!
object Foo4 extends Item1 with Item2 // aha!
In general you should avoid using override
where possible.
Upvotes: 10