In Scala, difference between final val and val

ScalaImmutability

Scala Problem Overview


In Scala, what is the difference between

val a = 1

and

final val fa = 1

Scala Solutions


Solution 1 - Scala

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

Solution 2 - Scala

In Scala, final declares that a member may not be overridden in subclasses. For example:

class Parent {
  val a = 1
  final val b = 2
}

class Subclass extends Parent {
  override val a = 3 // this line will compile
  override val b = 4 // this line will not compile
}

Also, as discussed in https://stackoverflow.com/questions/13412386/why-are-private-val-and-private-final-val-different, if a final val field is holding a "constant value", a constant primitive type, access to it will be replaced with the bytecode to load that value directly.

Solution 3 - Scala

You also cannot use non-final vals in (Java) annotations.

For example, this:

@GameRegistry.ObjectHolder(Reference.MOD_ID)
object ModItems{
}

will only compile if MOD_ID is declared as final.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionelmView Question on Stackoverflow
Solution 1 - ScalaMichael ZajacView Answer on Stackoverflow
Solution 2 - ScalawingedsubmarinerView Answer on Stackoverflow
Solution 3 - ScalaJinView Answer on Stackoverflow