Skip to content

A simple class to prevent NullPointerExceptions in Java

Notifications You must be signed in to change notification settings

mutkuensert/SafeCallJava

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 

Repository files navigation

SafeCallJava

A simple class to prevent NullPointerExceptions in Java

Java

import java.util.function.Supplier;

public class SafeCall {

    /**
     * Prevents NullPointerException
     */
    public static <T> T get(Supplier<T> supplier) {
        try {
            return supplier.get();
        } catch (NullPointerException e) {
            return null;
        }
    }
}

Kotlin

object SafeCall {

    /**
     * Prevents [NullPointerException] in java
     */
    @JvmStatic
    fun <T : Any> get(block: () -> T): T? {
        return try {
            block.invoke()
        } catch (e: NullPointerException) {
            null
        }
    }
}

Usage in Java

SafeCall.get(() -> getSomeObj().getProperty());

If getSomeObj method returns null, instead of occurence of a NullPointerException, SafeCall::get will return null.

Releases

No releases published

Packages

No packages published