Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand way for assigning object properties in Groovy?

I create Groovy objects using this convention...

Item item1 = new Item( name: "foo", weight: "150")

...is there a shorthand convention for manipulating properties object? something like this...

item1( name: "hello", weight: "175") //this does not work, btw ;-)

...instead of...

item1.name = "hello"
item1.weight = "175"
like image 571
raffian Avatar asked Dec 14 '11 16:12

raffian


People also ask

How do you define an object in Groovy?

A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain. A class in Groovy declares the state (data) and the behavior of objects defined by that class.

What are Groovy properties?

When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.

What is new keyword in Groovy?

The @Newify transformation annotation allows other ways to create a new instance of a class. We can use a new() method on the class or even omit the whole new keyword. The syntax is copied from other languages like Ruby and Python.

Is Groovy object oriented?

Groovy is a fully fledged object-oriented (OO) language supporting all of the OO programming concepts that are familiar to Java developers: classes, objects, interfaces, inheritance, polymorphism, and others.


2 Answers

You have the with method, as described by the great Mr Haki

item1.with{
    name = "hello"
    weight = "175"
}
like image 173
Grooveek Avatar answered Sep 21 '22 14:09

Grooveek


Yes, you can do it like this:

item1.metaClass.setProperties(item1, [name: "hello", weight: "175"])
like image 36
ataylor Avatar answered Sep 24 '22 14:09

ataylor