59

In Scala, what is the difference between

val a = 1

and

final val fa = 1
elm
  • 20,117
  • 14
  • 67
  • 113
  • Although that question is formulated from concurrency POV, the main answer discloses differences between val and final val. – om-nom-nom Jul 23 '14 at 16:05
  • It seems that `final val` allows the constant to be inlined into code that uses it: http://stackoverflow.com/a/13412894/14955 – Thilo Feb 25 '16 at 02:42

3 Answers3

76

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

Community
  • 1
  • 1
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
18

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 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.

Community
  • 1
  • 1
wingedsubmariner
  • 13,350
  • 1
  • 27
  • 52
4

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.

Tom S
  • 3
  • 2
Jin
  • 213
  • 1
  • 6