Skip to content

Instantly share code, notes, and snippets.

@Dierk
Created October 27, 2014 22:24
Show Gist options
  • Save Dierk/358a2bf24cdcd10044e8 to your computer and use it in GitHub Desktop.
Save Dierk/358a2bf24cdcd10044e8 to your computer and use it in GitHub Desktop.
A NullSafe Monad in Groovy with Java 8
import java.util.function.Function // requires Java 8
class NullSafe<T> {
protected final T t
protected NullSafe(T t) {this.t = t}
static NullSafe<T> enter(T t) { new NullSafe<T>(t) } // enter or "return" is like a constructor
// in the general case, applicative would have the type Function<T, NullSafe<T>> but we don't need that here
NullSafe<T> rightShift (Function<T,T> applicative) {
T result = applicative.apply(t) // here comes the Monad-specific binding logic
if (result == null) return this // in our case: ignore the nulls
enter(result)
}
}
NullSafe.enter("") >> // we cannot guarantee null safety for the intial value
{ "Hello " } >>
{ it * 2 } >>
{ it + "World" } >>
{ println it } >> // this returns null but we can proceed anyway
{ it + "!" } >>
{ println it // there is no other way to get onto the value then being in the Monad!
NullSafe.enter it } // not needed in our special case but better be a good citizen.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment