Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usage of a final var in Scala

Tags:

scala

What is the usage of a final var in Scala? What is the behavior. Are there any use cases?

(see also, Why are `private val` and `private final val` different?, which is very close, but not the same)

like image 298
Eran Medan Avatar asked Jan 13 '23 15:01

Eran Medan


1 Answers

final has overloaded meanings.

It can mean "can't override in subclasses", hence final var.

apm@mara:~$ skala -Yoverride-vars
Welcome to Scala version 2.11.0-20130811-132927-95a4d6e987 (OpenJDK 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> trait Foo { var v = 7 }
defined trait Foo

scala> trait Bar extends Foo { override var v = 8 }
defined trait Bar

scala> trait Foo { final var v = 7 }
defined trait Foo

scala> trait Bar extends Foo { override var v = 8 }
<console>:8: error: overriding variable v in class Foo$class of type Int;
 variable v cannot override final member
       trait Bar extends Foo { override var v = 8 }
                                            ^

final val i = 7 is a constant value definition (aka compile time constant) but val i = 7 is not, irrespective of the access modifier.

This has been quoted before, but, 5.2 of the spec:

The final modifier applies to class member definitions and to class defini- tions. A final class member definition may not be overridden in subclasses. A final class may not be inherited by a template. final is redundant for ob- ject definitions. Members of final classes or objects are implicitly also final, so the final modifier is generally redundant for them, too. Note, however, that constant value definitions (§4.1) do require an explicit final modifier, even if they are defined in a final class or object. final may not be applied to incom- plete members, and it may not be combined in one modifier list with sealed.

and 4.1

A constant value definition is of the form

final val x = e

where e is a constant expression (§6.24). The final modifier must be present and no type annotation may be given. References to the constant value x are themselves treated as constant expressions; in the generated code they are replaced by the def- inition’s right-hand side e.

Edit: sorry, didn't notice you specifically were not asking about that. The kids are getting ready for bed, tooth-brushing and all that, a bit distracted.

like image 179
som-snytt Avatar answered Jan 22 '23 20:01

som-snytt