Skip to content

Commit

Permalink
Merge pull request #2818 from lrytz/early-init-state
Browse files Browse the repository at this point in the history
Early init migration for another common use case
  • Loading branch information
lrytz authored Jul 17, 2023
2 parents 5720006 + bc4c407 commit 05ea648
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions _overviews/scala3-migration/incompat-dropped-features.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,46 @@ 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 {
private var added: Set[Int] = Set.empty
} with Adder {
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.
Expand Down

0 comments on commit 05ea648

Please sign in to comment.