Fred Friis
09/02/2019, 3:39 AMOption.else
vs Option.getOrElse
and
Either.filterOrElse
vs Either.filterOrOther
Imran/Malic
09/02/2019, 6:39 AMFred Friis
09/02/2019, 6:42 AMFred Friis
09/02/2019, 6:48 AMImran/Malic
09/02/2019, 8:20 AMsimon.vergauwen
09/02/2019, 9:20 AMfun <A> Option<A>.else(f: () -> Option<A>): Option<A>
fun <A> Option<A>.getOrElse(f: () -> A): A
So getOrElse
works similar to ?:
but instead of going from A?
-> A
you go from Option<A>
to A
.
else
works similarly but it doesn’t unwrap, so the result remains wrapped within Option
. Similar to null ?: null
, which is not allowed with getOrElse
.
So while ?:
can deal with more different situations the return type depends on the argument, which is not the case with else
or getOrElse
.simon.vergauwen
09/02/2019, 9:21 AMFred Friis
09/02/2019, 10:46 PMMike
09/03/2019, 12:34 PMEither.filterOrElse
and Either.filterOrOther
are the same under the covers except for one aspect.
If the predicate
is false, both call default
. filterOrElse
does not pass anything whereas filterOrOther
passes the value of the Either.
I added this as I was using filtering for error handling, and wanted to include information about the filtered out value in my errors. filterOrOther
allows it to flow nicely, where filterOrElse
required having the variable available somewhere in the more general scope.