From 5820696126f4d3b959f66157d5fc36d1d0d66c5b Mon Sep 17 00:00:00 2001 From: Lukas Rytz Date: Fri, 26 May 2023 11:45:04 +0200 Subject: [PATCH 1/2] Early init migration for another common use case --- .../incompat-dropped-features.md | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/_overviews/scala3-migration/incompat-dropped-features.md b/_overviews/scala3-migration/incompat-dropped-features.md index 4d5b2d5d7..03b4d35f8 100644 --- a/_overviews/scala3-migration/incompat-dropped-features.md +++ b/_overviews/scala3-migration/incompat-dropped-features.md @@ -226,6 +226,45 @@ class Fizz private (val name: String) extends Bar { {% endtab %} {% endtabs %} +Another use case for early initializers in Scala 2 is private state in the subclass that is accessed (through an overridden method) by the constructor of the superclass: + +{% tabs scala-2-initializer_5 %} +{% tab 'Scala 2 Only' %} +~~~ scala +class Adder { + var sum = 0 + def add(x: Int): Unit = sum += x + add(1) +} +class LogAdder extends Adder { + private var added: Set[Int] = Set.empty + override def add(x: Int): Unit = { added += x; super.add(x) } +} +~~~ +{% endtab %} +{% endtabs %} + +This case can be refactored by moving the private state into a nested `object`, which is initialized on demand: + +{% tabs shared-initializer_6 %} +{% tab 'Scala 2 and 3' %} +~~~ scala +class Adder { + var sum = 0 + def add(x: Int): Unit = sum += x + add(1) +} +class LogAdder extends Adder { + private object state { + var added: Set[Int] = Set.empty + } + import state._ + override def add(x: Int): Unit = { added += x; super.add(x) } +} +~~~ +{% endtab %} +{% endtabs %} + ## Existential Type Existential type is a [dropped feature]({{ site.scala3ref }}/dropped-features/existential-types.html), which makes the following code invalid. From bc4c407e8ed348389967ab36ebef6b4c9a966f87 Mon Sep 17 00:00:00 2001 From: Lukas Rytz Date: Fri, 26 May 2023 12:09:03 +0200 Subject: [PATCH 2/2] Update _overviews/scala3-migration/incompat-dropped-features.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sébastien Doeraene --- _overviews/scala3-migration/incompat-dropped-features.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/_overviews/scala3-migration/incompat-dropped-features.md b/_overviews/scala3-migration/incompat-dropped-features.md index 03b4d35f8..afdbe0022 100644 --- a/_overviews/scala3-migration/incompat-dropped-features.md +++ b/_overviews/scala3-migration/incompat-dropped-features.md @@ -236,8 +236,9 @@ class Adder { def add(x: Int): Unit = sum += x add(1) } -class LogAdder extends Adder { +class LogAdder extends { private var added: Set[Int] = Set.empty +} with Adder { override def add(x: Int): Unit = { added += x; super.add(x) } } ~~~