Reputation: 986
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.
Upvotes: 1
Views: 3142
Reputation: 3543
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.
Upvotes: 1
Reputation: 171144
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
Upvotes: 0
Reputation: 23748
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)
}
}
Upvotes: 1