An open API service indexing awesome lists of open source software.

https://github.com/mutkuensert/safecalljava

A simple class to prevent NullPointerExceptions in Java
https://github.com/mutkuensert/safecalljava

java kotlin null null-safe null-safety nullability nullpointerexception

Last synced: about 1 year ago
JSON representation

A simple class to prevent NullPointerExceptions in Java

Awesome Lists containing this project

README

          

# SafeCallJava
A simple class to prevent NullPointerExceptions in Java

#### Java

```Java
import java.util.function.Supplier;

public class SafeCall {

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

#### Kotlin

```kotlin
object SafeCall {

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

```

## Usage in Java
```Java
SafeCall.get(() -> getSomeObj().getProperty());
```

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