隐式类型转换?
我正在查看其他人的 Grails 代码,我看到以下内容:
Set<Integer> weeks = new ArrayList<Integer>()
看起来设置此行后,Grails 认为 week 是一个 HashSet
。我不太熟悉 Java 或 Grails,并且 (java) 文档看起来像 ArrayList 扩展 List 和 HashSet 扩展 Set,但这种直接构造不起作用。这是 Grails 的事情吗?谢谢。
I am reviewing someone else's Grails code and I see the following:
Set<Integer> weeks = new ArrayList<Integer>()
It looks like after this line is set, Grails thinks that weeks is a 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. Is this a Grails thing? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Groovy 中看到
new ArrayList()
有点不寻常,因为[]
的工作方式相同并且不那么冗长,所以我会将其写为Set< ;整数>周=[]
。然后就更清楚发生了什么 - Groovy 正在将一种集合类型转换为另一种集合类型,[]
实际上是创建持有者并填充初始数据(如果有)的便捷方法。由于除了List
和[:]
的[]
之外,集合没有任何语法糖,因此您需要这些转换。def week = [] as Set
可能是更常见的语法。这也更清楚,因为[]
只是临时的,使用“as”进行转换,并且比仅在左侧声明类型更明确。您还可以使用它将集合转换为数组。您不能使用 Java 语法来创建数组,因为它使用大括号并且看起来像闭包定义,因此您必须使用
int[]numbers = new int[] { 1, 2, 3 }
而不是执行int[]numbers = [1,2,3]
或defnumbers=[1,2,3]asint[]
。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 asSet<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). Since there's no syntactic sugar for collections other than[]
forList
and[:]
you need these conversions.def weeks = [] as Set
is probably the more common syntax. 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.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 doint[] numbers = [1, 2, 3]
ordef numbers = [1, 2, 3] as int[]
.