I have a domain class which has many of another domain class. I want any one of the children and don't care which. Example
class MyDomainClass {
static hasMany = [thingies:OtherDomainClass]
}
I can do this the stupid way like:
def findOne
myInstance.thingies.each{
findOne=it
}
But is there a better way like:
def findOne = myInstance.thingies.grabTheMostConvenientOne()
thingies
is a Collection, so you have everything from Collection at your disposal.
A simple way you might do this is:
def one = myInstance.thingies.asList().first()
However, you probably want to make sure the collection actually has some elements first. The documentation doesn't explicitly say that first()
throws an IndexOutOfBoundsException if the list is empty, but I have a feeling it still might. If that's the case, you probably want:
def one = myInstance.thingies.size() > 0 ? myInstance.thingies.asList().first() : null
Or, if you want to be super-concise at the expense of some readability, you can use this approach (courtesy John Wagenleitner):
def one = myInstance.thingies?.find { true }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With