anish
anish

Reputation: 7412

groovy closure for complex object

How can i write closure for below complex scenario

def empList=[];
EmployeeData empData = null;
empData=new EmployeeDataImpl("anish","nath");
empList.add(empData );
empData=new EmployeeDataImpl("JOHN","SMITH");
empList.add(empData );

Employee employee= new Employee(empList);

how can i write closure so that using emplyee object i will get empData details ? any hint Idea ?

Upvotes: 0

Views: 1057

Answers (1)

tim_yates
tim_yates

Reputation: 171064

I'm not sure what you mean...

To iterate over the EmployeeData, you could just use each:

empList.each { println it }

To find a particular entry, you can use find:

// Assume EmployeeData has a firstName property, you don't show its structure
EmployeeData anish = empList.find { it.firstName == 'anish' }

Or you can find all people with a given surname by using findAll:

def smiths = empList.findAll { it.surname == 'Smith' }

It depends what you want "the closure" to do...

Edit

Right, after you have explained your DSL that you want, I have come up with this (which will solve the given problem):

@groovy.transform.Canonical
class EmployeeData {
  String firstName
  String lastName
}

class Employee {
  List<EmployeeData> empList = []

  Employee( List<EmployeeData> list ) {
    empList = list
  }
}

class EmployeeDSL {
  Employee root

  List propchain = []

  EmployeeDSL( Employee root ) {
    this.root = root
  }

  def propertyMissing( String name ) {
    // if name is 'add' and we have a chain of names
    if( name == 'add' && propchain ) {
      // add a new employee
      root.empList << new EmployeeData( firstName:propchain.take( 1 ).join( ' ' ), lastName:propchain.drop( 1 ).join( ' ' ) )
      // and reset the chain of names
      propchain = []
    }
    else {
      // add this name to the chain of names
      propchain << name
      this
    }
  }
}

Employee emp = new Employee( [] )

new EmployeeDSL( emp ).with {
  anish.nath.add
  tim.yates.add
}

emp.empList.each {
  println it
}

It uses take() and drop(), so you will need groovy 1.8.1+

Hope it makes sense! It's a bit of an odd syntax however (using the keyword add to add the strings as an Employee), and instead of this it might be better to come up with something similar to MarkupBuilder by implementing BuilderSupport

Upvotes: 2

Related Questions