简体   繁体   English

在调用groovy闭包之前检查是否没有传递任何参数

[英]check if no parameters passed in groovy closure before calling it

i use maximumNumberOfParameters to check number of parameters used in closure ; 我使用maximumNumberOfParameters检查闭包中使用的参数数量;

   def callerCls(Closure c){
     prinltn 'Nb :'+c.maximumNumberOfParameters;
      c();
  }

the pb that the follwing snippet has the same result . 以下片段具有相同结果的铅。

  callerCls{


  }
 // and 
 callerCls{param1->

  }

Both of them return: 他们两个都返回:

Nb :1

Although the follwing code, returns Nb :2 . 尽管遵循以下代码,但返回Nb :2

 callerCls{p1,p2->

      }

How to distinguish closure where no parameter used (as the first snippet) ? 如何区分不使用参数的闭包(作为第一个代码段)?

Answer had been found in groovy official site groovy官方网站上找到答案

Parameter notes A Closure without -> , ie {} , is a Closure with one argument that is implicitly named as 'it'. 参数注释不带->的闭包(即{})是带有一个参数的闭包,其隐式命名为“ it”。 (see below for details) In some cases, you need to construct a Closure with zero arguments, eg using GString for templating, defining EMC Property etc. You have to explicity define your Closure as { -> } instead of just { } (有关详细信息,请参见下文)在某些情况下,您需要使用零参数构造一个Closure,例如,使用GString进行模板制作,定义EMC属性等。您必须将Closure明确定义为{->}而不是{}

You can also use varargs as parameters, refer to the Formal Guide for details. 您也可以将varargs用作参数,有关详细信息,请参考《正式指南》。 A JavaScript-style dynamic args could be simulated, refer to the Informal Guide. 可以模拟JavaScript样式的动态参数,请参考《非正式指南》。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM