Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shortcut to execute something only if its not null? [duplicate]

Tags:

java

I find myself constantly writing this statement

MyObject myObject = something.getThatObject();
if( myObject !=null &&
    myObject .someBooleanFunction()){

}

in order to prevent a null pointer exception. Is there a shortcut to this in Java? I'm thinking like myObject..someBooleanFunction()?

like image 687
Carlos Bribiescas Avatar asked May 29 '14 18:05

Carlos Bribiescas


1 Answers

In Java 8:

static <T> boolean notNull(Supplier<T> getter, Predicate<T> tester) {
    T x = getter.get();
    return x != null && tester.test(x);
}

    if (notNull(something::getThatObject, MyObject::someBooleanFunction)) {
        ...
    }

If this style is new to the readers, one should keep in mind, that full functional programming is a bit nicer.

like image 77
Joop Eggen Avatar answered Sep 28 '22 05:09

Joop Eggen