Skip to content

Instantly share code, notes, and snippets.

@lachezar
Created November 15, 2023 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lachezar/0debc046b81c863b0c96fc8cda586ceb to your computer and use it in GitHub Desktop.
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.
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