Skip to content

Add subsection "Default Parameters for Overloaded Methods" #2646

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 9 commits into from
Nov 21, 2022
21 changes: 21 additions & 0 deletions _tour/default-parameter-values.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,24 @@ public class Main {
```
{% endtab %}
{% endtabs %}

### Default Parameters for Overloaded Methods

It's important to notice that Scala doesn't allow having two methods with default parameters and with the same name (overloaded).

For example, if you write `def f(a: Int = 1)`, the compiler generates `def f$default$1 = 1`. If you have two overloads with defaults on the same parameter position, then we would need a different naming scheme. In this situation, it is preferred to keep the generated byte-code stable over multiple compiler runs.

An important reason why is to avoid the ambiguity that can be caused due to the existence of default parameters. To illustrate the problem, let's consider the method declarations provided below:

{% tabs default-parameter-values-5 %}
{% tab 'Scala 2 and 3' for=default-parameter-values-5 %}
```scala mdoc:fail
object A {
def func(x: Int = 34): Unit
def func(y: String = "abc"): Unit
}
```
{% endtab %}
{% endtabs %}

If we call `A.func()`, compiler cannot know whether the programmer intended to call `func(x: Int = 34)` or `func(y: String = "abc")`.