Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, difference between final val and val [duplicate]

In Scala, what is the difference between

val a = 1 

and

final val fa = 1 
like image 666
elm Avatar asked Jul 23 '14 13:07

elm


People also ask

What is difference between Val and VAR in Scala?

The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable.

What is final keyword in Scala?

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.

What is Val in Scala?

Differences between var and val keywords in Scala Variable defined are mutable variables. Variables defined are immutable variables. Values are not constant for var variables. Values are constant for val variables.

Can a VAL be changed in Scala?

In short: No, you cannot.


1 Answers

final members cannot be overridden, say, in a sub-class or trait.

Legal:

class A {     val a = 1 }  class B extends A {     override val a = 2 } 

Illegal:

class A {     final val a = 1 }  class B extends A {     override val a = 2 } 

You'll get an error such as this:

:9: error: overriding value a in class A of type Int(1);

value a cannot override final member

like image 167
Michael Zajac Avatar answered Sep 19 '22 09:09

Michael Zajac