Skip to content

Instantly share code, notes, and snippets.

@rascio
Last active March 4, 2016 14:39
Show Gist options
  • Save rascio/353dc5d21effe2195781 to your computer and use it in GitHub Desktop.
Save rascio/353dc5d21effe2195781 to your computer and use it in GitHub Desktop.
package it.r.rapportini.utils.optional;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Created by rascio on 26/02/16.
*/
public class OptionalUtils {
public static class OptionalPatternMatching<T> {
private final Optional<T> optional;
private OptionalPatternMatching(Optional<T> optional) {
this.optional = optional;
}
public <R> IfPresent<T, R> present(Function<T, R> ifPresent) {
return new IfPresent<>(this.optional, ifPresent);
}
public VoidIfPresent<T> present(Consumer<T> ifPresent) {
return new VoidIfPresent<>(this.optional, ifPresent);
}
public VoidIfPresent<T> present(RuntimeException exception) {
return present((Consumer<T>) t -> {
throw exception;
});
}
}
public static class IfPresent<T, R> {
private final Optional<T> optional;
private final Function<T, R> ifPresent;
private IfPresent(Optional<T> optional, Function<T, R> ifPresent) {
this.optional = optional;
this.ifPresent = ifPresent;
}
public R absent(Supplier<R> ifAbsent) {
return optional.map(ifPresent)
.orElseGet(ifAbsent);
}
public R absent(RuntimeException exception) {
return optional.map(ifPresent)
.orElseThrow(() -> exception);
}
public R or(R alternative) {
return absent(() -> alternative);
}
}
public static class VoidIfPresent<T> extends IfPresent<T, Void> {
private VoidIfPresent(Optional<T> optional, Consumer<T> ifPresent) {
super(optional, t -> {
ifPresent.accept(t);
return null;
});
}
public void absent(Runnable ifAbsent) {
super.absent(() -> {
ifAbsent.run();
return null;
});
}
}
public static <T> OptionalPatternMatching<T> match(Optional<T> optional) {
if (optional == null) {
throw new IllegalArgumentException("The optional can't be null");
}
return new OptionalPatternMatching<>(optional);
}
}
@rascio
Copy link
Author

rascio commented Mar 4, 2016

Using it:

public static void main(String[] args) {
    Integer length = OptionalUtils.match(findSomething())
        .present(s -> {
            System.out.println("The String is present " + s);
            return s.length(); //The return is optional
        })
        .absent(() -> {
            System.out.println("The string is absent");
            return 0; //The return is optional
       });
}

public static Optional<String> findSomething() {
    return Optional.empty();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment