为什么可以在没有任何参数的情况下调用具有单个参数的构造函数?

Max*_*dev 5 groovy

class Foo {
  public Foo(String s) {}
}
print new Foo()
Run Code Online (Sandbox Code Playgroud)

为什么这段代码有效?

如果我使用基本类型的参数声明构造函数,则脚本将失败.

tim*_*tes 4

Groovy 将尽力完成您要求它做的事情。当您调用时new Foo(),它与调用相匹配new Foo( null ),因为有一个可以接受null值的构造函数。

如果您让构造函数采用原始类型,则 this 不能为null,因此 Groovy 会抛出Could not find matching constructor for: Foo()异常,如您所见。

它对方法执行相同的操作,因此:

class Test {
  String name
  
  Test( String s ) {
    this.name = s ?: 'tim'
  }
  
  void a( String prefix ) {
    prefix = prefix ?: 'Hello'
    println "$prefix $name"
  }
}

new Test().a()
Run Code Online (Sandbox Code Playgroud)

打印Hello tim(因为构造函数和方法都是使用 null 参数调用的)

然而:

new Test( 'Max' ).a( 'Hola' )
Run Code Online (Sandbox Code Playgroud)

印刷Hola Max

澄清

在 Groovy User 邮件列表上询问,得到了以下答复:

这对任何方法调用都有效(不仅是构造函数),而且我(以及其他人)真的不喜欢这个“功能”(因为它很容易出错),所以它可能会在 Groovy 3 中消失。而且,静态编译不支持它:)

所以,它可以工作(目前),但不要依赖它:-)