In Scala, difference between final val and val

elm picture elm · Jul 23, 2014 · Viewed 17.5k times · Source

In Scala, what is the difference between

val a = 1

and

final val fa = 1

Answer

Michael Zajac picture Michael Zajac · Jul 23, 2014

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