From e817eb1f4c0cd05164a15961f463dcd0196e744a Mon Sep 17 00:00:00 2001 From: Fengyun Liu Date: Wed, 2 Oct 2024 20:30:15 +0200 Subject: [PATCH 1/2] Add a test --- tests/init-global/warn/Color.scala | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 tests/init-global/warn/Color.scala diff --git a/tests/init-global/warn/Color.scala b/tests/init-global/warn/Color.scala new file mode 100644 index 000000000000..ee1c00701940 --- /dev/null +++ b/tests/init-global/warn/Color.scala @@ -0,0 +1,10 @@ +enum Color: + case None, White, Black + +enum Player: + case Black, White + + val color: Color = + if this == Player.Black // warn + then Color.Black + else Color.White From ca7553ed9d81e4327f6998be77bb0f061f1be936 Mon Sep 17 00:00:00 2001 From: Fengyun Liu Date: Sat, 5 Oct 2024 09:48:54 +0200 Subject: [PATCH 2/2] Add explanation for code --- tests/init-global/warn/Color.scala | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/init-global/warn/Color.scala b/tests/init-global/warn/Color.scala index ee1c00701940..59554c905cd0 100644 --- a/tests/init-global/warn/Color.scala +++ b/tests/init-global/warn/Color.scala @@ -4,7 +4,25 @@ enum Color: enum Player: case Black, White + // Explanation: See the desugaring below val color: Color = if this == Player.Black // warn then Color.Black else Color.White + +// From the desugaring of Player, we can see the field `Player.Black` is not yet +// initialized during evaluation of the first `new Player`: +// +// class Player: +// val color: Color = +// if this == Player.Black ... +// +// object Player: +// val Black: Player = new Player // <--- problem +// val White: Player = new Player +// +// +// The complex desugaring makes it difficult to see the initialization +// semantics and it is prone to make such hard-to-spot mistakes. +// +// Note: The desugaring above is simplified for presentation.