Named parameters: Difference between revisions

Content added Content deleted
(Replace println() with print(); replace output "syntaxhighlight" tag with "pre" tag)
Line 588: Line 588:
A common example of using named arguments is a "wither" method:
A common example of using named arguments is a "wither" method:
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
module NamedParams
module NamedParams {
const Point(Int x, Int y) {
{
const Point(Int x, Int y)
Point with(Int? x=Null, Int? y=Null) {
{
Point with(Int? x=Null, Int? y=Null)
{
return new Point(x ?: this.x, y ?: this.y);
return new Point(x ?: this.x, y ?: this.y);
}
}
}
}


@Inject Console console;
@Inject Console console;


void run()
void run() {
{
Point origin = new Point(0, 0);
Point origin = new Point(0, 0);
console.print($"origin={origin}");
console.print($"origin={origin}");
Point moveRight = origin.with(x=5);
Point moveRight = origin.with(x=5);
console.print($"moveRight(x=5)={moveRight}");
console.print($"moveRight(x=5)={moveRight}");
Point moveUp = moveRight.with(y=3);
Point moveUp = moveRight.with(y=3);
console.print($"moveUp(y=3)={moveUp}");
console.print($"moveUp(y=3)={moveUp}");
}
}
}
}
</syntaxhighlight>
</syntaxhighlight>