com.github.tonivade.purefun.Matcher1 Maven / Gradle / Ivy
/*
* Copyright (c) 2018-2021, Antonio Gabriel Muñoz Conejo
* Distributed under the terms of the MIT License
*/
package com.github.tonivade.purefun;
import static com.github.tonivade.purefun.Precondition.checkNonNull;
import static java.util.Objects.nonNull;
import java.util.Objects;
import java.util.stream.Stream;
@FunctionalInterface
public interface Matcher1 extends Recoverable {
default boolean match(A target) {
try {
return run(target);
} catch (Throwable t) {
return sneakyThrow(t);
}
}
boolean run(A target) throws Throwable;
default Function1 asFunction() {
return this::match;
}
default Matcher1 and(Matcher1 super A> other) {
return value -> match(value) && other.match(value);
}
default Matcher1 or(Matcher1 super A> other) {
return value -> match(value) || other.match(value);
}
default Matcher1 negate() {
return value -> !match(value);
}
@SuppressWarnings("unchecked")
static Matcher1 not(Matcher1 super A> matcher) {
return (Matcher1) matcher.negate();
}
static Matcher1 never() {
return value -> false;
}
static Matcher1 always() {
return value -> true;
}
static Matcher1 invalid() {
return value -> { throw new IllegalStateException(); };
}
// XXX: when I change Class> for Class extends T>
// javac complains about this, it cannot infer type parameters but inside eclipse works fine
static Matcher1 instanceOf(Class> type) {
checkNonNull(type);
return value -> nonNull(value) && type.isAssignableFrom(value.getClass());
}
static Matcher1 is(A other) {
checkNonNull(other);
return value -> Objects.equals(value, other);
}
@SafeVarargs
static Matcher1 isIn(A... values) {
checkNonNull(values);
return target -> Stream.of(values).anyMatch(value -> Objects.equals(target, value));
}
static Matcher1 isNull() {
return Objects::isNull;
}
static Matcher1 isNotNull() {
return Objects::nonNull;
}
@SafeVarargs
static Matcher1 allOf(Matcher1 super A>... matchers) {
checkNonNull(matchers);
return target -> Stream.of(matchers).allMatch(matcher -> matcher.match(target));
}
@SafeVarargs
static Matcher1 anyOf(Matcher1 super A>... matchers) {
checkNonNull(matchers);
return target -> Stream.of(matchers).anyMatch(matcher -> matcher.match(target));
}
static Matcher1 otherwise() {
return value -> true;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy