Named parameters: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Replace println() with print(); replace output "syntaxhighlight" tag with "pre" tag)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(3 intermediate revisions by 2 users not shown)
Line 588:
A common example of using named arguments is a "wither" method:
<syntaxhighlight lang="java">
module NamedParams {
const Point with(Int? x=Null, Int? y=Null) {
{
const 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);
}
}
{}
 
@Inject Console console;
 
void run() {
{
Point origin = new Point(0, 0);
console.print($"origin={origin}");
Point moveRight = origin.with(x=5);
console.print($"moveRight(x=5)={moveRight}");
Point moveUp = moveRight.with(y=3);
console.print($"moveUp(y=3)={moveUp}");
}
}
}
</syntaxhighlight>
 
Line 2,098 ⟶ 2,094:
whatever bar:=1, baz:=2, foo:=-1, qux:="Why is ev'rybody always pickin' on me?"
End Sub</syntaxhighlight>
 
=={{header|V (Vlang)}}==
1) Vlang allows for a struct literal to be passed to the function, instead of named parameters.
 
2) Using this style, fields need not appear in the same order as they are declared.
 
3) If one or more fields are omitted, their default values will be used instead.
 
4) The named parameter feature was deliberately omitted, for greater code readability.
 
5) Depending on the situation, variadic and/or sum types can also be considered.
<syntaxhighlight lang="Zig">
struct Params {
a int
b int
c int
}
 
fn a_fn(p Params) int {
return p.a + p.b + p.c
}
 
fn main() {
x := a_fn(Params{a: 1, b: 2, c: 3}) // same order
println("x = ${x}")
y := a_fn(Params{c: 3, b: 2, a: 1}) // different order
println("y = ${y}")
z := a_fn(Params{c: 2}) // only one field
println("z = ${z}")
}
</syntaxhighlight>
 
{{out}}
<pre>
x = 6
y = 6
z = 2
</pre>
 
=={{header|Wren}}==
Wren doesn't support named parameters as such though they can be simulated using a map.
<syntaxhighlight lang="ecmascriptwren">var printName = Fn.new { |name|
if (!(name is Map && name["first"] != null && name["last"] != null)) {
Fiber.abort("Argument must be a map with keys \"first\" and \"last\"")
9,477

edits