diff --git a/compiler/src/dotty/tools/dotc/transform/init/Objects.scala b/compiler/src/dotty/tools/dotc/transform/init/Objects.scala index 1ceb8d4472a3..1050fbe85ef2 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Objects.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Objects.scala @@ -908,7 +908,10 @@ class Objects(using Context @constructorOnly): Bottom } - /** Handle new expression `new p.C(args)`. + /** + * Handle new expression `new p.C(args)`. + * The actual instance might be cached without running the constructor. + * See tests/init-global/pos/cache-constructor.scala * * @param outer The value for `p`. * @param klass The symbol of the class `C`. @@ -950,7 +953,6 @@ class Objects(using Context @constructorOnly): val instance = OfClass(klass, outerWidened, ctor, args.map(_.value), envWidened) callConstructor(instance, ctor, args) - instance case ValueSet(values) => values.map(ref => instantiate(ref, klass, ctor, args)).join diff --git a/tests/init-global/pos/cache-constructor.scala b/tests/init-global/pos/cache-constructor.scala new file mode 100644 index 000000000000..87769fd5d78a --- /dev/null +++ b/tests/init-global/pos/cache-constructor.scala @@ -0,0 +1,8 @@ +class Bar: + var f: Int = 0 + +object A: + val b1 = new Bar() + val b2 = new Bar() + val b3 = new Bar() + b3.f = 1