hippocrene
hippocrene

Reputation: 84

Reference an instance of a class by a property in Groovy

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

Answers (2)

injecteer
injecteer

Reputation: 20699

define children as map:

Map<String,Child> children

then

parent.children.bob

or

parent.children[ 'bob' ]

Upvotes: 1

tim_yates
tim_yates

Reputation: 171054

Just add a method to Parent to do it:

Child children(String name) {
    children.find { it.name == name }
}

Upvotes: 2

Related Questions