Groovy web console

subscribe to the feed Subscribe
to this
site

asdf

Published 2 months ago by Anonymous
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
class Person {
    ContactInformation contactInformation
}

class ContactInformation {
    Set<Phone> phone
}

class Phone {
    String number
}

def persons = [
        new Person(contactInformation: [phone: [new Phone(number: "123456789")]]),
        new Person(contactInformation: [phone: [new Phone(number: "987654321")]]),
        new Person(contactInformation: [phone: [new Phone(number: "123654789")]]),
        new Person(contactInformation: [phone: [new Phone(number: "321987456")]])
] as Set<Person>

// Pay attention to the scope of returns and closure return types
static Person findPersonIncorrect(Set<Person> persons, String number) {
    // persons.any accepts a closure, that is an anonymous function or piece of between {}
    // 'any' method expects the closure to return a boolean or boolean-ish value
    persons.any { person ->
        // Here you're using another any for phone numbers (I'm assuming phone is a collection)
        person.contactInformation.phone.any { phone ->
            if (phone.number == number) {
                // here you're not returning the person object from the 'findPerson' method
                // you're returning the person object from the 'person.contactInformation.phone.any'
                // method and that methods return type is boolean so that person object
                // will be coerced into a boolean true as non-null objects are 'truthy' values
                return person
            }
        }
        // so then here you have the value 'true' (not person object)
    }
    // and here you have the value 'true' which is completely ignored
    return null // and then you always return null, completely foregoing whatever you've done beforehand
    // (as this is the only return in the scope of the actual 'findPerson' method)
}

static Person findPersonCorrect(Set<Person> persons, String number) {
    // Groovy has an extension method called 'find' which does what you actually wanted to accomplish
    // It tries to find whatever the predicate returns true for and returns null if nothing is found
    return persons.find { person ->
        // in this case, find the first person which contains the given phone number
        // this any will return 'true' if the person contains that phone number
        // that 'true' will then be returned to find
        // and find will return the person object for which it received 'true'
        person.contactInformation.phone.any { phone -> phone.number == number }
    }
}

def person = findPersonIncorrect(persons, "123456789")

println person == null

person = findPersonCorrect(persons, "123456789")

println person != null
println person?.contactInformation?.phone?.first()?.number