VOOZH about

URL: https://www.geeksforgeeks.org/scala/scala-final/

⇱ Scala | Final - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Scala | Final

Last Updated : 2 Sep, 2021

In Scala, Final is a keyword and used to impose restriction on super class or parent class through various ways. We can use final keyword along with variables, methods and classes. Following are the ways of using final keyword in Scala

  1. Scala Final Variable: Scale final variable initialized only once while declared and used as constant throughout the program. In below example, variable area is final which is declared as final and also initialized while declare in superclass shapes. if we want to access or modify the variable area from derived class Rectangle then it is not possible because the restriction on variable area is added by keyword final.

    Scala final variable initialized by following ways:

    • While declaring
    • In static block
    • In Constructor
    Following error occurs while running above code Output :
     
    prog.scala:5: error: overriding value area in class Shapes of type Int;
     value area cannot override final member
    override val area:Int = 100
     ^
    one error found
    
  2. Scala Final Methods: Final method CalArea in the parent class (Shapes) indicate that, method cannot override in a child class (Rectangle). Following error occurs while running above code Output :
    prog.scala:8: error: overriding method CalArea in class Shapes of type ()Unit;
     method CalArea cannot override final member
     override def CalArea(){
     ^
    one error found
    
  3. Scala Final Classes If the class in Scala is final then it cannot inherit to derived class. Inheritance restriction will be added by final keyword. Here if class Shapes are final then its all members also final and cannot used in derived class. Following error occurs while running above code Output :
     
    prog.scala:4: error: illegal inheritance from final class Shapes
    class Rectangle extends Shapes{
     ^
    one error found
    
Comment
Article Tags:
Article Tags:

Explore