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: 21 days 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

```kotlin
/**
* Prevents [NullPointerException] in java
*/
object SafeCall {

@JvmStatic
fun get(block: () -> T): T? {
return try {
block.invoke()
} catch (_: NullPointerException) {
null
}
}

@JvmStatic
fun getOrElse(block: () -> T, default: T): T {
return try {
block.invoke()
} catch (_: NullPointerException) {
default
}
}

@JvmStatic
fun call(block: Runnable) {
try {
block.run()
} catch (_: NullPointerException) {
}
}
}

```

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

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