Reputation: 84
Given the following:
class Parent {
private String name,
private List<Child> children
}
class Child {
private String name
}
I'd like to be able to refer to a specific child by using:
parent.children('bob')
Instead of by index:
parent.children[0]
How would this be done in Groovy?
Upvotes: 0
Views: 154
Reputation: 20699
define children as map:
Map<String,Child> children
then
parent.children.bob
or
parent.children[ 'bob' ]
Upvotes: 1
Reputation: 171054
Just add a method to Parent
to do it:
Child children(String name) {
children.find { it.name == name }
}
Upvotes: 2