简体   繁体   English

Groovy Closure通用返回/参数?

[英]Groovy Closure generic return/parameters?

I have a method that should take a Closure with first two parameters Car and Tyre and should return a type of Vehicle. 我有一个方法,应该使用前两个参数Car和Tire进行Closure,并应该返回一种Vehicle类型。

Is there a way to declare the type of parameters in Groovy Closures? 是否可以在Groovy闭包中声明参数的类型?

I am thinking 我在想

method(Closure<Vehicle, Car, Tyre> closure); 

but what is the correct way? 但是正确的方法是什么?

You can only define the return type of a Closure, ie: Closure<Vehicle> 您只能定义Closure的返回类型,即: Closure<Vehicle>

As of Groovy 2.3, you can use @ClosureParam to tweak the type system (see "Tweaking the type system" here ), but Groovy 2.3 is not currently in Grails I believe... 从Groovy 2.3开始,您可以使用@ClosureParam调整类型系统(请参阅此处的 “调整类型系统” ),但是我相信Groovy 2.3当前不在Grails中...

The generic parameter on Closure is used for the return type. Closure上的通用参数用于返回类型。 Closure<String> shall return a string. Closure<String>应返回一个字符串。

The parameters may be declared using the @ClosureParams annotation 可以使用@ClosureParams批注来声明参数

http://beta.groovy-lang.org/docs/groovy-2.3.0-beta-1/html/gapi/groovy/transform/stc/ClosureParams.html http://beta.groovy-lang.org/docs/groovy-2.3.0-beta-1/html/gapi/groovy/transform/stc/ClosureParams.html

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

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