哪种编程语言允许方法参数的默认值?

时间:2010-10-07 19:42:35

标签: programming-languages

我很好奇哪些语言允许你这样做:

method foo(String bar = "beh"){

}

如果你这样打电话给foo:

foo();

bar将设置为“beh”,但如果您这样打电话:

foo("baz");

bar将设置为“baz”。

14 个答案:

答案 0 :(得分:8)

我可以想到

  • C#4.0
  • C ++
  • VB.Net(所有版本)
  • VB6
  • F#(仅限会员)
  • Powershell的
  • IDL
  • 红宝石

答案 1 :(得分:8)

  • 几乎所有Lisps
  • 红宝石
  • 的Python
  • C ++
  • C#
  • Visual Basic.NET
  • 的Tcl
  • Visual Basic
  • 伊欧凯
  • SEPH
  • 眼镜蛇
  • Nemerle
  • 米拉
  • 的Delphi
  • Groovy的
  • PHP
  • 花式
  • Scala的

答案 2 :(得分:6)

PHP:

function foo($var = "foo") {
    print $var;
}

foo(); // outputs "foo"
foo("bar"); // outputs "bar"

Python

def myFun(var = "foo"):
    print var

Ruby

def foo(var="foo")
    print var
end

Groovy:

def foo(var="foo") {
    print var
}

答案 3 :(得分:3)

Racket提供了这个,以及关键字参数:

(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

它们在documentation中描述。

答案 4 :(得分:2)

从c#4.0起,您现在可以使用默认参数。终于来了!

C ++,Ruby和VB

答案 5 :(得分:2)

自从1999年发布的第5版以来,Delphi已经允许这样做

procedure foo(const bar: string = 'beh');
begin
...
end;

foo;
foo('baz');

答案 6 :(得分:2)

Perl使用Method::Signatures

答案 7 :(得分:2)

的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

答案 8 :(得分:2)

TCL提供此功能

proc procName {{arg1 defaultValue} {arg2 anotherDefaultValue}} {
    # proc body
}

答案 9 :(得分:1)

D

void foo(int x, int y = 3)
{
   ...
}
...
foo(4);   // same as foo(4, 3);

Fantom

class Person
{
  Int yearsToRetirement(Int retire := 65) { return retire - age }

  Int age
}

答案 10 :(得分:0)

Java有一个解决方法。

你可以让foo方法没有参数调用foo方法,参数设置默认值,如下所示:

void foo() {
   foo("beh");
}

void foo(String bar) {
   this.bar = bar;
}

答案 11 :(得分:0)

添加到列表Realbasic(事实上,Realbasic几乎包含了我能想到的每种语言的所有特性,包括内省和沙盒脚本)。

的Python。 (但请注意每http://effbot.org/zone/default-values.htm

的变量

许多语言,包括C,允许可变数量的参数,这些参数可以有效地让你做同样的事情。

在许多现代脚本语言中,包括PHP,JavaScript和Perl,处理此类事物的更好的习惯是允许关联数组或对象作为参数,然后根据需要分配默认值。

e.g。

function foo( options ){
  if( options.something === undefined ){
    options.something = some_default_value;
  }
  ...
}

这消除了将默认值放在参数列表末尾并记住您不想覆盖的所有内容的必要性。

一如既往 - 适度使用。

答案 12 :(得分:0)

您可以在PL / SQL中执行此操作。

答案 13 :(得分:-1)

我知道Python允许这样做,而C,C ++则没有。

相关问题