I'm curious which languages allow you to do something like this:
method foo(String bar = "beh"){
}
If you call foo like this:
foo();
bar
will be set to "beh", but if you call like this:
foo("baz");
bar
will be set to "baz".
I'm curious which languages allow you to do something like this:
method foo(String bar = "beh"){
}
If you call foo like this:
foo();
bar
will be set to "beh", but if you call like this:
foo("baz");
bar
will be set to "baz".
as of c# 4.0 you can now have default params. Finally!
Also C++, Ruby and VB
Ones I can think of
function foo($var = "foo") {
print $var;
}
foo(); // outputs "foo"
foo("bar"); // outputs "bar"
def myFun(var = "foo"):
print var
def foo(var="foo")
print var
end
def foo(var="foo") {
print var
}
Delphi has allowed this since about version 5 - released in 1999
procedure foo(const bar: string = 'beh');
begin
...
end;
foo;
foo('baz');
Java has a workaround.
You can have the foo method with no parameters that calls the foo method with parameters setting the default value, like this:
void foo() {
foo("beh");
}
void foo(String bar) {
this.bar = bar;
}
Python:
def foo(bar = value):
# This function can be invoked as foo() or foo(something).
# In the former case, bar will have its default value.
pass
Add to the list Realbasic (indeed Realbasic has almost every nice feature of every language I can think of, including introspection and sandboxed scripting).
Python. (But watch out for mutables per http://effbot.org/zone/default-values.htm )
And plenty of languages, including C, allow variable numbers of parameters which effectively lets you do the same thing.
In many modern scripting languages, including PHP, JavaScript, and Perl, a better idiom for handling such things is to allow an associative array or object as a parameter, and then assign defaults if needed.
e.g.
function foo( options ){
if( options.something === undefined ){
options.something = some_default_value;
}
...
}
This eliminates the necessity of putting the defaultable values at the end of the list of parameters and remembering all the stuff you don't want to override.
As always -- use in moderation.
TCL provides this functionality
proc procName {{arg1 defaultValue} {arg2 anotherDefaultValue}} {
# proc body
}
D:
void foo(int x, int y = 3)
{
...
}
...
foo(4); // same as foo(4, 3);
class Person
{
Int yearsToRetirement(Int retire := 65) { return retire - age }
Int age
}
Racket provides this, as well as keyword arguments:
(define (f x [y 0]) (+ x y))
(f 1) ; => 1
(f 10 20) ; => 30
(define (g x #:y [y 0]) (- x y))
(g 1) ; => 1
(g 10 #:y 20) ; => -10
They're described in the documentation.