Groovy access multiple member variable

Is there any convention like this in groovy to access member variables

class Emp {
   String name
   String name1
}

Emp emp = new Emp()
emp {
  name = "name"
  name1 = "name1"
}

rather than repeating the object again and again

emp.name = "name"
emp.name1 = "name1"

Somewhere I have seen a convention like this

Upvotes: 0

Views: 52

Answers (2)

GUL
GUL

Reputation: 1195

You can use

Emp emp = new Emp(name: "name", name1: "name1")

See http://www.groovy-lang.org/style-guide.html#_initializing_beans_with_named_parameters_and_the_default_constructor

Upvotes: 1

jalopaba
jalopaba

Reputation: 8119

You can use with:

class Emp {
   String name
   String name1
}

Emp emp = new Emp()
emp.with {
  name = 'name'  // -> emp.name = 'name'
  name1 = 'name1'  // -> emp.name1 = 'name1'
}

assert emp.name == 'name'
assert emp.name1 == 'name1'

Upvotes: 1

Related Questions