Skip to content

Early init migration for another common use case #2818

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 17, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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