简体   繁体   中英

Implicit Type Conversion?

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.

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 = [] . 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 [] for List 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 do int[] numbers = [1, 2, 3] or def numbers = [1, 2, 3] as int[] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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