Style Guide - UBOdin/mimir GitHub Wiki
Var vs Val
By default prefer using val
over var
. Reasonable exceptions include:
Lazy Loading
When initialization of a class object needs to be decoupled from allocation (e.g., because of a cyclic allocation dependency). Example: Objects in Database are initialized as part of db.init()
. Before using var
in this way, consider whether the same effect might be accomplished by a lazy val
.
Staged Transformation
Some parts of the code iteratively apply a sequence of transformations to a value. For example, Compiler's deploy
method conditionally applies several transformations to the oper
object. val
-based alternatives are generally inferior:
- Unique names for the variable at every stage: Every time you add a new stage, you need to remember to update names both before and after the new stage. This has caused numerous bugs.
- A big giant match statement: Exponential code complexity with tons of repetition.
Staged transformations are a case where var
is preferred.