1

I have the following code:

class User {
    String id = ""
}

class Customer {
    String id = ""
    User[] users
}

Customer[] customers = new Customer[5]

for (i=0;i<numCustomers;i++) {
    customers[i] = new Customer()
    customers[i].id = "customer:" + (1000+i)
    customers[i].users = new User[3]
    for (j=0; j<users.size(); j++) {
         customers[i].users[j] = new User()
         customers[i].users[j].id = customers[i].id 
    }
}

The initialization of the customers array seems correct. If I only have the "id" field it works fine. However, when I added the "users" field, with the code showed above I get "No such property: users" on the line:

customers[i].users = new User[3]

Why is this? Also, I am new to Groovy, so please point out any other issue with my code above.

2
  • 2
    in for (j=0; j<users.size(); j++) what is the users ? I guess you meant customers[i].users ... Commented Mar 7, 2014 at 17:35
  • Indeed, thank you. I overlooked it, also because the editor I'm using at the moment is not pointing out where the error is. Thought for sure it was on the previous line. Commented Mar 7, 2014 at 19:37

3 Answers 3

1
 for (j=0; j<users.size(); j++) {

is the line causing trouble. No users variable is defined in the class running your script. Judging from you code, you probably wanted to use

 for (j=0; j<customers[i].users.size(); j++) {

For the future, I suggest using an IDE, IntelliJ has a really nice Groovy support.

Sign up to request clarification or add additional context in comments.

Comments

1

In your example you're creating customers[i].users = new User[3] but testing users.size() in loop when assigning users to the custumer.

Assuming numCustomers = 5 try something like the folowing:

for (i=0; i < numCustomers; i++) {
    Customer customer = new Customer()
    customers[i] = customer
    customer.id = "customer:" + (1000+i)
    customer.users = new User[3]
    for (j=0; j < 3; j++) {
         User user = new User()
         user.id = customer.id
         customer.users[j] = user
    }
}

If you wanted to replace array of users with a List then it could look like this:

class Customer {
    String id = ""
    List<User> users = new ArrayList<User>()
}

for (i=0; i < numCustomers; i++) {
  // ...
  for (j=0; j < 3; j++) {
    User user = new User()
    user.id = customer.id
    customer.users.add(user)
  }
}

Comments

0

How about

Customer[] customers = (1000..1005).collect { id ->
    new Customer( id:"$id", users:(1..3).collect {
        new User( id:"$id" )
    } )
}

Not tried it, but I think it's OK

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.