Last active
November 26, 2019 15:58
-
-
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/
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
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 | |
} |
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
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