Skip to content

Commit 9acb354

Browse files
KarahanSbishabosha
andauthored
Add subsection "Default Parameters for Overloaded Methods" (#2646)
* Add subsection "Default Parameters for Overloaded Methods" Add a subsection to [Default Parameter Values](https://docs.scala-lang.org/tour/default-parameter-values.html) as to why we can't use default parameters for more than one overloaded method. Sources: * https://groups.google.com/g/scala-user/c/FyQK3-cqfaY/m/fXLHr8QsW_0J * https://stackoverflow.com/a/10927256/16530078 * Update default-parameter-values.md * Update default-parameter-values.md * Update _tour/default-parameter-values.md Co-authored-by: Jamie Thompson <bishbashboshjt@gmail.com> * Update _tour/default-parameter-values.md Co-authored-by: Jamie Thompson <bishbashboshjt@gmail.com> * Update _tour/default-parameter-values.md Co-authored-by: Jamie Thompson <bishbashboshjt@gmail.com> * Remove dots from scala expression * Update the description * Separate Scala 3 and Scala 2 Co-authored-by: Jamie Thompson <bishbashboshjt@gmail.com> Co-authored-by: Jamie Thompson <bishbashboshjt@gmail.com>
1 parent 75fdff7 commit 9acb354

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

_tour/default-parameter-values.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,28 @@ public class Main {
6262
```
6363
{% endtab %}
6464
{% endtabs %}
65+
66+
### Default Parameters for Overloaded Methods
67+
68+
Scala doesn't allow having two methods with default parameters and with the same name (overloaded).
69+
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:
70+
71+
{% tabs default-parameter-values-5 class=tabs-scala-version %}
72+
{% tab 'Scala 2' %}
73+
```scala mdoc:fail
74+
object A {
75+
def func(x: Int = 34): Unit
76+
def func(y: String = "abc"): Unit
77+
}
78+
```
79+
{% endtab %}
80+
{% tab 'Scala 3' %}
81+
```scala
82+
object A:
83+
def func(x: Int = 34): Unit
84+
def func(y: String = "abc"): Unit
85+
```
86+
{% endtab %}
87+
{% endtabs %}
88+
89+
If we call `A.func()`, compiler cannot know whether the programmer intended to call `func(x: Int = 34)` or `func(y: String = "abc")`.

0 commit comments

Comments
 (0)