Scala Field Overriding

In Scala, we can override the fields but with some rules. Let’s understand it with some examples.

If you look at the below code, where we are overriding the field named ‘age’ from 30 to 35. It will give the compile time error saying “Variable ‘age’ needs override modifier”.

Compile time error

As a solution, we must use either override keyword or override annotation while overriding any method or field of super class.Let’s see below the solution of above problem.

One important point to note here is that we can override only those variables which are declared by using val keyword, not by var keyword. If we use override keyword with var, it throws the error message as “variable age cannot override a mutable variable”

Scala - This Keyword
Scala Final
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *