Created
November 15, 2023 13:11
-
-
Save lachezar/0debc046b81c863b0c96fc8cda586ceb to your computer and use it in GitHub Desktop.
Java Optional that forces you to deal with the missing value on compile-time level instead of the runtime.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example; | |
import java.util.Optional; | |
import java.util.Random; | |
import java.util.function.Supplier; | |
class NPEChecked extends Exception implements Supplier<NPEChecked> { | |
private static final NPEChecked instance = new NPEChecked(); | |
@Override | |
public NPEChecked get() { | |
return instance; | |
} | |
public static NPEChecked supplier() { | |
return instance; | |
} | |
} | |
public class Main { | |
private static Integer saferOptionals() throws NPEChecked { | |
return (new Random().nextBoolean() ? Optional.of(42) : Optional.<Integer>empty()) | |
.orElseThrow(NPEChecked.supplier()); | |
} | |
public static void main(String... args) { | |
try { | |
Integer x = saferOptionals(); | |
System.out.printf("It was Some(%d)%n", x); | |
} catch (NPEChecked e) { | |
System.out.println("It was None"); | |
} | |
} | |
/* | |
* You can always re-throw the checked exception to the next caller. | |
* Unfortunately to transform the `None` into something resembling `Left(err)` | |
* you'd have to catch and throw new exception. | |
* | |
* It becomes very verbose very fast 🙀. | |
*/ | |
public static void main2(String... args) throws NPEChecked { | |
Integer x = saferOptionals(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment