Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TupleConstructor with named parameters

Tags:

groovy

I have this Script:

def person = new Person(lastName: "foo", firstName: "bar")

println person

@groovy.transform.TupleConstructor  
@groovy.transform.ToString(includeNames = true, includeFields=true)  
class Person
{  
   def lastName  
   def firstName  
}

why it gives me:

Person(lastName:[lastName:foo, firstName:bar], firstName:null)

Why firstName remains null and lastName has the map of the parameters?

I am using groovy 1.8.6

like image 331
res1 Avatar asked Dec 16 '13 19:12

res1


Video Answer


1 Answers

Because you have your fields declared as def, the TupleConstructor is effectively adding 2 constructors:

Person( Object first name )

And

Person( Object firstName, Object secondName )

Then, when you call the map style constructor, it is calling the one arg tuple constructor with the map as the parameter.

Adding types to your fields should remove this issue

As it says in the docs for TupleConstructor:

Limitations: - Groovy's normal map-style naming conventions will not be available if the first property (or field) has type LinkedHashMap or if there is a single Map, AbsotractMap or HashMap property (or field)

like image 194
tim_yates Avatar answered Sep 25 '22 13:09

tim_yates