Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: what is the purpose of 'override'

Tags:

scala

I'm not sure what the purpose of override keyword is, in scala. If I have

trait Shape { def foo(v: Int) } class Triangle extends Shape { override def foo(v: Int) {} } 

it behaves (apparently at least) exactly the same as it does without override.

like image 972
user1377000 Avatar asked Apr 19 '13 17:04

user1377000


People also ask

What is override in Scala?

This is the concept of Scala method overriding and we use the 'override' modifier to implement this. Let's see Scala String Method with Syntax and Method. Technically, Scala method overriding is when a member M of class C matches a non-private member M' of a class from which C inherits.

What is the purpose of overriding?

The purpose of Method Overriding is that if the derived class wants to give its own implementation it can give by overriding the method of the parent class. When we call this overridden method, it will execute the method of the child class, not the parent class.

What happens if you don't use @override?

If you don't use the annotation, the sub-class method will be treated as a new method in the subclass (rather than the overriding method). 2) It improves the code's readability.

Is it mandatory to use @override?

@Override annotation is used when we override a method in sub class. Generally novice developers overlook this feature as it is not mandatory to use this annotation while overriding the method.


1 Answers

In the case you are implementing an abstract method as in your example, it is not strictly necessary to add the override modifier.

However, in case you want to override a concrete method from the superclass, the override modifier is necessary. This is to avoid accidental overrides which could happen with mixing composition -- mixing-in traits during some refactoring could easily introduce a method definition that could be overridden by the method defined in the body of the class, hence the need for explicitly stating that a method is an override.

like image 155
axel22 Avatar answered Sep 29 '22 08:09

axel22