6

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()
Mikey
  • 4,692
  • 10
  • 45
  • 73

1 Answers1

9

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 }
Community
  • 1
  • 1
Rob Hruska
  • 118,520
  • 32
  • 167
  • 192