Skip to content

Instantly share code, notes, and snippets.

@YSMull
Created June 8, 2018 19:14
Show Gist options
  • Save YSMull/5b22f2e7e2f801807734fb6cff017897 to your computer and use it in GitHub Desktop.
Save YSMull/5b22f2e7e2f801807734fb6cff017897 to your computer and use it in GitHub Desktop.
package chkr;
@FunctionalInterface
interface CheckedFunction<T, R> {
R apply(T t) throws Exception;
}
-----------
package chkr;
import java.util.function.Function;
public class Extend {
public CheckedFunction fn;
Extend(){}
Extend(CheckedFunction fn) {
this.fn = fn;
}
@SuppressWarnings("unchecked")
public Extend match(CheckedFunction check) {
return new Extend(value -> {
try {
return check.apply(value);
} catch (Exception e) {
throw new Exception(e.getMessage());
}
});
}
@SuppressWarnings("unchecked")
public Extend judge(Function<Object, Boolean> cond, String message) {
return match(value -> {
if (fn != null) fn.apply(value);
if (cond.apply(value)) {
return value;
} else {
throw new Exception(message);
}
});
}
@SuppressWarnings("unchecked")
public Object check(Object value) throws Exception {
return fn.apply(value);
}
}
----------------
package chkr;
import java.util.Map;
import java.util.Objects;
public class T {
public static Extend Null = new Extend().judge(Objects::isNull, "is not Null");
public static Extend Any = new Extend().judge(Objects::nonNull, "is Null");
public static Extend Num() throws Exception {
return Any.judge(a -> {
try {
int b = (int) a;
return true;
} catch (Exception e){
return false;
}
}, "is not Num");
}
public static Extend Str() {
return Any.judge(a -> {
try {
String b = (String) a;
return true;
} catch (Exception e){
return false;
}
}, "is not Str");
}
public static Extend Or(Extend... es) {
return new Extend().match(value -> {
boolean matchSome = false;
for (Extend e : es) {
try {
e.check(value);
matchSome = true;
break;
} catch (Exception exp) {
}
}
if (matchSome) {
return value;
} else {
throw new Exception("Or failed");
}
});
}
public static void main(String[] args) {
try {
System.out.println(Num().check(null)); // throw error
System.out.println(Num().check(123)); // 123
System.out.println(Num().check("abc")); // throw error
System.out.println(Str().check(null)); // throw error
System.out.println(Str().check("abc")); // abc
System.out.println(Str().check(123)); // throw error
System.out.println(Or(Str(), Num()).check(123)); // 123
System.out.println(Or(Str(), Num()).check("abc")); // abc
System.out.println(Or(Str(), Num()).check(true)); // throw error
var typeCheck = Map.of(
"userId", Num(),
"userName", Str(),
"phone", Str(),
"IdCard", Or(Num(), Str())
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment