Skip to content

Commit 2498cf9

Browse files
authored
Merge pull request #1879 from dotty-staging/fix-final-vars
Fix #1878: Generate fields for final vars.
2 parents 3922cce + 63d68bf commit 2498cf9

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

compiler/src/dotty/tools/dotc/transform/Memoize.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ import Decorators._
102102
case _ => t
103103
}
104104
skipBlocks(tree.rhs) match {
105-
case lit: Literal if sym.is(Final) && isIdempotentExpr(tree.rhs) =>
105+
case lit: Literal if sym.is(Final, butNot = Mutable) && isIdempotentExpr(tree.rhs) =>
106106
// duplicating scalac behavior: for final vals that have rhs as constant, we do not create a field
107107
// and instead return the value. This seemingly minor optimization has huge effect on initialization
108108
// order and the values that can be observed during superconstructor call

tests/run/final-var.check

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
false
2+
true
3+
false
4+
true

tests/run/final-var.scala

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
object Test {
2+
def main(args: Array[String]): Unit = {
3+
println(Obj.myFinalVar)
4+
Obj.myFinalVar = true
5+
println(Obj.myFinalVar)
6+
7+
val o = new Cls
8+
println(o.myFinalVar)
9+
o.myFinalVar = true
10+
println(o.myFinalVar)
11+
}
12+
}
13+
14+
object Obj {
15+
final var myFinalVar: Boolean = false
16+
}
17+
18+
class Cls {
19+
final var myFinalVar: Boolean = false
20+
}

0 commit comments

Comments
 (0)