Groovy方法调用语法 [英] Groovy method call syntax

查看:1159
本文介绍了Groovy方法调用语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处的教程说:


如果至少有一个参数并且没有歧义,则Groovy中的方法调用可以省略括号。




 静态方法1(def val1)
{
Statement.method1:$ val1
}

def method1retval = method1 30;
println(method1retval); //Statement.method1:30

但是当我为该方法添加另一个参数时:

  static method1(def val1,def val2)
{
Statement.method1:$ val1 $ val2
}
def method1retval = method1 3020;
println(method1retval);

它给出错误

 线程main中的异常groovy.lang.MissingMethodException:没有方法签名:static Statements.method1()适用于参数类型:(java.lang.Integer)values:[30] 
可能的解决方案:method1(int,java.lang.String)

strong>在方法调用中有多个参数时,我不能省略括号?



Q 也可以在调用类构造函数时省略括号吗?

解决方案

然后调用 method1 30,20。文档说你可以省略(和)而不是。在你的情况下,代码将被解释为 method1(30)。20(做下一个调用)。

<对于一般的构造函数,适用相同的规则。但通常它们与 new 一起使用,这是行不通的。

  class A {
A(){println(X)}
A(x,y){println([x,y])}
}

// new A // FAILS
// new A 1,2 FAILS

A.newInstance 1,2 //作品

围绕 new 的错误表明,是预期的,并且它们已经在parsetime失败了。 new 是一个关键字并且具有特殊行为。 这一切都归结为:避免()使代码变得更好(如果你使用代码打高尔夫,则更短)。主要用于DSL将代码转换为可读句子(例如从table中选择*,其中x> 6或grails 静态约束{myval nullable:true ,min:42} )。


A tutorial here says:

Method calls in Groovy can omit the parenthesis if there is at least one parameter and there is no ambiguity.

This works:

static method1(def val1)
{
    "Statement.method1 : $val1"
}

def method1retval = method1 30; 
println (method1retval);  //Statement.method1 : 30

But when I add another parameter to the method:

static method1(def val1, def val2)
{
    "Statement.method1 : $val1 $val2"
}
def method1retval = method1 30 "20";
println (method1retval);

It gives error

Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: static Statements.method1() is applicable for argument types: (java.lang.Integer) values: [30]
Possible solutions: method1(int, java.lang.String)

Q. So cant I omit parenthesis when having more than one parameters in method call?

Q. Also can we omit parenthesis when calling class constructor?

解决方案

the call then is method1 30, "20". The docs say you can omit ( and ) but not the ,. In your case the code would be interpreted as method1(30)."20" (do the next call).

As for constructors in general the same rule applies. But usually they are used with new and this does not work.

class A {
    A() { println("X") }
    A(x,y) { println([x,y]) }
}

// new A // FAILS
// new A 1,2 FAILS

A.newInstance 1,2 // works

The errors around new indicate, that a ( is expected and that they already fail at parsetime. new is a keyword and holds special behaviour.

In reality this all comes down to: avoiding the () to make code nicer (or shorter, if you code-golf). It's primary use is for "DSL" where you would just turn code into readable sentences (e.g. select "*" from "table" where "x>6" or in grails static constraints { myval nullable: true, min: 42 }).

这篇关于Groovy方法调用语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆