Skip to content

Instantly share code, notes, and snippets.

@dfa1
Last active November 26, 2019 15:58
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 dfa1/f6fdca0513730dc7dc7d6a5d89629709 to your computer and use it in GitHub Desktop.
Save dfa1/f6fdca0513730dc7dc7d6a5d89629709 to your computer and use it in GitHub Desktop.
(run-time) Refined types in Java https://kwark.github.io/refined-in-practice/
import java.util.function.Predicate;
public class Refined<T> {
private final T value;
public Refined(Predicate<T> validator, T value) {
if (validator.test(value)) {
throw new IllegalArgumentException();
}
this.value = value;
}
public final T getValue() {
return value;
}
// provide equals/hashCode/toString
}
import java.util.function.Predicate;
public class Refining {
public static PositiveInt of(int value) {
return new PositiveInt(value);
}
public static Age of(int value) {
return new Age(value);
}
private static class PositiveInt extends Refined<Integer> {
public PositiveInt(Integer value) {
super(i -> i > 0, value);
}
}
private static class Age extends Refined<Integer> {
public Age(Predicate<Integer> validator, Integer value) {
super(v -> v > 0 && v < 120, value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment