These may seem a bit simple for DGMs, but they do solve a couple problems as
compared to "list ? list.first() ?: defaultValue". First, no repetition of the
"list" expression, which may be complex. Second, content assist will show
proposals for these methods. Third, the Groovy truth problems with "list?[0]
?: defaultValue", "list?.getAt(0) ?: defaultValue", "list.find() ?:
defaultValue" and others do not exist for these. If the first element is null
or otherwise falsy, it will be returned as desired. The only case for me that
is unresolved is a null array or iterable. In this case, Groovy throws "Cannot
invoke method firstOrElse() on null obect" instead of running the method
allowing null tolerance and return of default value.
public static T firstOrElse(Iterable self, T defaultValue) {
Iterator iter = self.iterator();
if (iter.hasNext()) {
return iter.next();
}
return defaultValue;
}
public static T firstOrElse(T[] self, T defaultValue) {
if (self.length > 0) {
return self[0];
}
return defaultValue;
}
// and similarly for the Closure (or java.util.function.Supplier if Java 8+
only) variants
Since safe navigation is being explored for by-index access, is there a
possibility for including some for of "or supplied default" in any of the
safe-navigation cases? I personally find the new safe-indexing syntax to be
unnecessary when "list?.getAt(i)" appears to be the equivalent to "list?[i]".
Alternate proposal, what if the DGM.getAt(self, int idx) had variants that
included a default value return instead of hard-coded null? Like this:
public static T getAt(List self, int idx, T def) {
int size = self.size();
int i = normaliseIndex(idx, size);
if (i < size) {
return self.get(i);
} else {
//return null;
return def;
}
}
From: Mario Garcia
Sent: Thursday, October 18, 2018 6:19 PM
To: dev@groovy.apache.org
Subject: Re: DGM for first or default
Good point OC:
[0,'',[],[:]].find()?:'not quite what you wanted here'
[0,1,2].find()?:'nor in this case'
The more I think on this the more I think is an interesting topic. I fully
understand your frustration with first(), but apart from the example with Cocoa
you mentioned, looking in the JVM it turns out there're plenty of examples of
language collections behaving that way:
In scala the head of an empty list does throw an exception
---
scala> var empty = List[Int]()
empty: List[Int] = List()
scala> empty.head
java.util.NoSuchElementException: head of empty list
at scala.collection.immutable.Nil$.head(List.scala:426)
at scala.collection.immutable.Nil$.head(List.scala:423)
... 28 elided
scala>
-
and so does kotlin when calling to first()
--
Welcome to Kotlin version 1.2.71 (JRE 1.8.0_171-b11)
Type :help for help, :quit for quit
>>> val num: List = listOf()
>>> num.first()
java.util.NoSuchElementException: List is empty.
at kotlin.collections.CollectionsKt___CollectionsKt.first(_Collections.kt:184)
>>>
-
in Kotlin they have firstOrNull(), but I haven't found any overloaded function
with a default value. They also have "find", but it's not possible to call it
without parameter
However Clojure returns null whether:
* The first element was nil
* The list was empty
* Or the list was nil
user=> (def a nil)
#'user/a
user=> a
nil
user=> (first a)
nil
user=> (def a '(nil))
#'user/a
user=> a
(nil)
user=> (first a)
nil
user=> (def a '())
#'user/a
user=> a
()
user=> (first a)
nil
user=>
---
BTW I forgot to mention that Groovy 3 will have safe indexing meaning an
expression like the following:
* will return the first element of a non empty list which I guess it will
be the Kotlin firstOrNull() equivalent
* or null if the list was null or empty
-
// trying to get first element from null list
nullList?[0] ==> null
// trying to get an inexistent element from a non empty list (but this is not
new, this is how a non empty list indexing works in Groovy)
nonNullList?[] => null
--
Outside the JVM, Haskell, when asking for the head of an empty list, throws an
exception (There is an explanation in stackoverflow which I'm afraid I don't
understand). So in the end Groovy's first() seems not to be the exception among
other modern languages out there.
Another point of view, could be thinking about returning null consistently.
Lets say a list returns null using first():
* Does it mean the first element is a null value or is an empty list and
that's why is giving me a null value ?
* What if null is a valid value, with some meaning in my process ? With
that context a method like firstOrNull() (even first(defaultValue) with a null
list) could be considered