Skip to content

Commit 05ea648

Browse files
authored
Merge pull request #2818 from lrytz/early-init-state
Early init migration for another common use case
2 parents 5720006 + bc4c407 commit 05ea648

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

_overviews/scala3-migration/incompat-dropped-features.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,46 @@ class Fizz private (val name: String) extends Bar {
226226
{% endtab %}
227227
{% endtabs %}
228228

229+
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:
230+
231+
{% tabs scala-2-initializer_5 %}
232+
{% tab 'Scala 2 Only' %}
233+
~~~ scala
234+
class Adder {
235+
var sum = 0
236+
def add(x: Int): Unit = sum += x
237+
add(1)
238+
}
239+
class LogAdder extends {
240+
private var added: Set[Int] = Set.empty
241+
} with Adder {
242+
override def add(x: Int): Unit = { added += x; super.add(x) }
243+
}
244+
~~~
245+
{% endtab %}
246+
{% endtabs %}
247+
248+
This case can be refactored by moving the private state into a nested `object`, which is initialized on demand:
249+
250+
{% tabs shared-initializer_6 %}
251+
{% tab 'Scala 2 and 3' %}
252+
~~~ scala
253+
class Adder {
254+
var sum = 0
255+
def add(x: Int): Unit = sum += x
256+
add(1)
257+
}
258+
class LogAdder extends Adder {
259+
private object state {
260+
var added: Set[Int] = Set.empty
261+
}
262+
import state._
263+
override def add(x: Int): Unit = { added += x; super.add(x) }
264+
}
265+
~~~
266+
{% endtab %}
267+
{% endtabs %}
268+
229269
## Existential Type
230270

231271
Existential type is a [dropped feature]({{ site.scala3ref }}/dropped-features/existential-types.html), which makes the following code invalid.

0 commit comments

Comments
 (0)