Last active
April 1, 2017 07:48
-
-
Save kilaka/658990a96a05e5a21fc5ee8588b9c583 to your computer and use it in GitHub Desktop.
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
package kilaka; | |
public class LambdaUtil { | |
/** | |
* Works only with Java 8. | |
*/ | |
@SuppressWarnings("unchecked") | |
public static <T extends Throwable> RuntimeException rethrowSneaky(Throwable throwable) throws T { | |
throw (T) throwable; // rely on vacuous cast | |
} | |
@FunctionalInterface | |
public interface Function<T, R> { | |
R apply(T t) throws Exception; | |
static <T, R> java.util.function.Function<T, R> unchecked(Function<T, R> f) { | |
return t -> { | |
try { | |
return f.apply(t); | |
} catch (Exception e) { | |
throw rethrowSneaky(e); | |
} | |
}; | |
} | |
} | |
public static <T, R> java.util.function.Function<T, R> unchecked(Function<T, R> f) { | |
return Function.unchecked(f); | |
} | |
@FunctionalInterface | |
public interface Predicate<T> { | |
boolean test(T t) throws Exception; | |
static <T> java.util.function.Predicate<T> unchecked(Predicate<T> p) { | |
return t -> { | |
try { | |
return p.test(t); | |
} catch (Exception e) { | |
throw rethrowSneaky(e); | |
} | |
}; | |
} | |
} | |
public static <T> java.util.function.Predicate<T> unchecked(Predicate<T> p) { | |
return Predicate.unchecked(p); | |
} | |
@FunctionalInterface | |
public interface Consumer<T> { | |
void accept(T t) throws Exception; | |
static <T> java.util.function.Consumer<T> unchecked(Consumer<T> c) { | |
return t -> { | |
try { | |
c.accept(t); | |
} catch (Exception e) { | |
throw rethrowSneaky(e); | |
} | |
}; | |
} | |
} | |
public static <T> java.util.function.Consumer<T> unchecked(Consumer<T> c) { | |
return Consumer.unchecked(c); | |
} | |
// public static <T, R> R nullProtect(T t, java.util.function.Function<T, R> f) { | |
// if (t == null) return null; | |
// return f.apply(t); | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment