Last active
March 4, 2016 14:39
-
-
Save rascio/353dc5d21effe2195781 to your computer and use it in GitHub Desktop.
This file contains 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 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using it: