简体   繁体   中英

Changed behavior in object field access in Groovy 3.0?

I've recently stumbled on this issue when assisting in the migration of some legacy code.

The following used to execute correctly in Groovy 2.4.x:

class Person {
  String name
}

def me = new Person( name : 'Joe' )

assert me.(name) == 'Joe'

while it raises an exception when executed on Groovy 3.0.2:

groovy.lang.MissingPropertyException: No such property: name for class: MyScript

Enclosing the property name in parentheses actually looks wrong to me: as a matter of fact, I was surprised that an exception was not raised in older releases too.

The syntax I would probably have used is either:

assert me.name == 'Joe'

or something like:

assert me.'name' == 'Joe'

which work in both versions 2.4 AND 3.0.

I did some research and couldn't find anything in the Changelogs from Groovy 2.4 through Groovy 3.0 that refers to something that could affect this behavior.

Am I missing something here?

Was the fact that the code worked in 2.4 an unexpected behavior, which has been corrected? Or is this actually expected to work?

My guess is that it has to do with the switch to the new Parrot parser in version 3.0.

Thanks!

When you wrap the property name in parens, like "me.(name)", you are using dynamic property syntax. Groovy is supposed to resolve "name" in the enclosing scope and not against the receiver. If you want to get the "name" property from "me", you can write "me.name" or "me.'name'" or "me['name']" or "me.getProperty('name')".

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