Skip to content
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

Add tabs tour named args #2521

Merged
merged 2 commits into from
Sep 13, 2022
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
18 changes: 15 additions & 3 deletions _tour/named-arguments.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,38 @@ next-page: traits
previous-page: default-parameter-values
prerequisite-knowledge: function-syntax

redirect_from:
redirect_from:
- "/tutorials/tour/named-arguments.html"
- "/tutorials/tour/named-parameters.html"
---

When calling methods, you can label the arguments with their parameter names like so:

{% tabs named-arguments-when-good %}

{% tab 'Scala 2 and 3' for=named-arguments-when-good %}
```scala mdoc
def printName(first: String, last: String): Unit = {
def printName(first: String, last: String): Unit =
println(first + " " + last)
}

printName("John", "Smith") // Prints "John Smith"
printName(first = "John", last = "Smith") // Prints "John Smith"
printName(last = "Smith", first = "John") // Prints "John Smith"
```
{% endtab %}

{% endtabs %}

Notice how the order of named arguments can be rearranged. However, if some arguments are named and others are not, the unnamed arguments must come first and in the order of their parameters in the method signature.

{% tabs named-arguments-when-error %}

{% tab 'Scala 2 and 3' for=named-arguments-when-error %}
```scala mdoc:fail
printName(last = "Smith", "john") // error: positional after named argument
```
{% endtab %}

{% endtabs %}

Named arguments work with calls to Java methods, but only if the Java library in question was compiled with `-parameters`.