Groovy methods that resemble LINQ's DefaultIfEmpty and FirstOrDefault
groovy, linq
Solution
`DefaultIfEmpty` can be covered by:
def list = []
def defaultIfEmpty = list ?: [ 'was empty' ]
`FirstOrDefault` is trickier, as I believe it returns the default value for a given type if there is no first element in the list... However, in Groovy (as it stands), there's no way of detecting the default type of the object (unless it is a native type)
You could do:
Integer defaultIfEmpty = list[ 0 ] ?: 0
It should be noticed however that the `elvis operator ?:` works on Groovy truth, so if the element on the left of the operator evaluates to false in Groovy (whether it be `null`, an empty list or string, the number 0, etc) it will return the right hand side)
It should also be noted that I am not a .NET expert, so may have the functionality of these two functions incorrect.
Problem
Does Groovy have any methods (out-of-the-box) that resemble the DefaultIfEmpty or FirstOrDefault methods found in LINQ?