简体   繁体   English

隐式类型转换?

[英]Implicit Type Conversion?

I am reviewing someone else's Grails code and I see the following: 我正在查看其他人的Grails代码,并且看到以下内容:

Set<Integer> weeks = new ArrayList<Integer>()

It looks like after this line is set, Grails thinks that weeks is a HashSet . 设置此行后,Grails认为周是HashSet I am not well versed in either Java or Grails, and the (java) documentation looks like ArrayList extends List and HashSet extends Set, but that this direct construction wouldn't work. 我对Java或Grails都不熟悉,并且(java)文档看起来像ArrayList扩展了List并且HashSet扩展了Set,但是这种直接构造不起作用。 Is this a Grails thing? 这是Grails的东西吗? Thanks. 谢谢。

It's somewhat unusual in Groovy to see new ArrayList<Integer>() since [] works identically and is way less verbose, so I would have written that as Set<Integer> weeks = [] . 在Groovy中,看到new ArrayList<Integer>()有点不寻常,因为[]工作原理相同,而且不太冗长,所以我将其写为Set<Integer> weeks = [] Then it's a bit more clear what's going on - Groovy is converting one collection type to another, with the [] really as a convenient way to create a holder and populate the initial data (if there is any). 然后,事情就变得更加清楚了-Groovy正在将一种集合类型转换为另一种集合类型,而[]确实是创建保存器并填充初始数据(如果有)的便捷方法。 Since there's no syntactic sugar for collections other than [] for List and [:] you need these conversions. 由于除了[]List[:]之外,没有用于集合的语法糖,您需要这些转换。

def weeks = [] as Set is probably the more common syntax. def weeks = [] as Set可能是更常见的语法。 This is also more clear since [] is just temporary and using "as" does the conversion, and more explicitly than just declaring the type on the left side. 这也更加清楚,因为[]只是临时的,使用“ as”进行转换,并且比仅在左侧声明类型更明确。

You can also use this to convert collections to arrays. 您还可以使用它来将集合转换为数组。 You can't use Java syntax to create arrays since it uses braces and looks like a Closure definition, so instead of int[] numbers = new int[] { 1, 2, 3 } you have to do int[] numbers = [1, 2, 3] or def numbers = [1, 2, 3] as int[] . 您不能使用Java语法来创建数组,因为它使用花括号并且看起来像一个闭包定义,因此您必须使用int[] numbers = [1, 2, 3]代替int[] numbers = new int[] { 1, 2, 3 } int[] numbers = [1, 2, 3]def numbers = [1, 2, 3] as int[]

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

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