Skip to content

Commit 9f879bb

Browse files
committed
Fix 2396b: Non-static synthetic case-objects should be initialized early.
Lazy val implements non-static objects. But if object is not user-defined we don't make it `real` lazy, we instead make it eager as no-one will notice. This actually saves resources as otherwise you'll still need to initialize lazy-val related stuff in constructor instead and later initialize actual objects. Those objests, being eager, should be initialized early, so that constructors can't see un-initialized values.
1 parent ad2bb89 commit 9f879bb

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,9 +252,17 @@ class Constructors extends MiniPhaseTransform with IdentityDenotTransformer { th
252252
case _ => superCalls
253253
}
254254

255+
// Lazy Vals may decide to create an eager val instead of a lazy val
256+
// this val should be assigned before constructor body code starts running
257+
258+
val (lazyAssignments, stats) = followConstrStats.partition {
259+
case Assign(l, r) if l.symbol.name.is(NameKinds.LazyLocalName) => true
260+
case _ => false
261+
}
262+
255263
cpy.Template(tree)(
256264
constr = cpy.DefDef(constr)(
257-
rhs = Block(copyParams ::: mappedSuperCalls ::: followConstrStats, unitLiteral)),
265+
rhs = Block(copyParams ::: mappedSuperCalls ::: lazyAssignments ::: stats, unitLiteral)),
258266
body = clsStats.toList)
259267
}
260268
}

tests/run/i2396b.scala

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Bees {
2+
def f: PartialFunction[Bee, Unit] = { case Bee(_) => "" }
3+
4+
f(new Bee("buzz"))
5+
6+
case class Bee(value: String)
7+
//object Bee // With this it works
8+
}
9+
10+
object Test {
11+
def main(args: Array[String]): Unit = {
12+
new Bees
13+
}
14+
}

0 commit comments

Comments
 (0)