加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

groovy – 为什么可以在没有任何参数的情况下调用带有单个参数的

发布时间:2020-12-14 16:28:21 所属栏目:大数据 来源:网络整理
导读:class Foo { public Foo(String s) {}}print new Foo() 为什么这段代码有效? 如果我使用基本类型的参数声明构造函数,则脚本将失败. 解决方法 Groovy将尽力做你要求它做的事情.当你调用new Foo()时,它匹配调用new Foo(null)的调用,因为有一个可以取空值的构
class Foo {
  public Foo(String s) {}
}
print new Foo()

为什么这段代码有效?

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

解决方法

Groovy将尽力做你要求它做的事情.当你调用new Foo()时,它匹配调用new Foo(null)的调用,因为有一个可以取空值的构造函数.

如果你使构造函数采用原始类型,那么这不能为null,因此Groovy会抛出一个找不到匹配的构造函数: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()

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

wheras:

new Test( 'Max' ).a( 'Hola' )

打印Hola Max

澄清

我asked on the Groovy User mailing list,得到以下回复:

This is valid for any method call (not only constructors) and I (as well as others) really dislike this “feature” (because it’s very error prone) so it will probably disappear in Groovy 3. Also,it’s not supported by static compilation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读