Skip to content

Instantly share code, notes, and snippets.

@josejuan
Last active April 30, 2018 14:51
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 josejuan/a3bbba503979a2c023f11626b8415844 to your computer and use it in GitHub Desktop.
Save josejuan/a3bbba503979a2c023f11626b8415844 to your computer and use it in GitHub Desktop.
package man;
import static com.xxx.fp.Either.left;
import static com.xxx.fp.Either.right;
import static java.lang.String.format;
import com.xxx.fp.Either;
import java.util.function.Function;
public class Main {
final static Function<String, Either<String, String>> notEmpty =
s -> s.isEmpty() ? left("must not be empty") : right(s);
static class User {
String name;
Integer age;
public User(Integer age, String name) {
this.age = age;
this.name = name;
}
public Integer getAge() {
return age;
}
public String getName() {
return name;
}
}
static Function<Integer, Either<String, Integer>> greaterThan(final Integer x) {
return n -> n > x ? right(n) : left(format("should be greater than %d", x));
}
static Function<Integer, Either<String, Integer>> lessThan(final Integer x) {
return n -> n < x ? right(n) : left(format("should be less than %d", x));
}
static <T, K> Function<T, Either<String, T>> using(final Function<T, K> l, Function<K, Either<String, K>> k) {
return t -> k.apply(l.apply(t)).map(ignore -> t);
}
public void main(final String... args) {
final Either<String, User> safeUser =
Either.<String, User>right(new User(44, "Peter"))
.bind(using(User::getAge, greaterThan(18)))
.bind(using(User::getAge, lessThan(18)))
.bind(using(User::getName, notEmpty));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment