Skip to content

Commit 5820696

Browse files
committed
Early init migration for another common use case
1 parent b4ce6a6 commit 5820696

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,45 @@ 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 Adder {
240+
private var added: Set[Int] = Set.empty
241+
override def add(x: Int): Unit = { added += x; super.add(x) }
242+
}
243+
~~~
244+
{% endtab %}
245+
{% endtabs %}
246+
247+
This case can be refactored by moving the private state into a nested `object`, which is initialized on demand:
248+
249+
{% tabs shared-initializer_6 %}
250+
{% tab 'Scala 2 and 3' %}
251+
~~~ scala
252+
class Adder {
253+
var sum = 0
254+
def add(x: Int): Unit = sum += x
255+
add(1)
256+
}
257+
class LogAdder extends Adder {
258+
private object state {
259+
var added: Set[Int] = Set.empty
260+
}
261+
import state._
262+
override def add(x: Int): Unit = { added += x; super.add(x) }
263+
}
264+
~~~
265+
{% endtab %}
266+
{% endtabs %}
267+
229268
## Existential Type
230269

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

0 commit comments

Comments
 (0)