I have the following code
public class FunctionalInterfaceTest {
@FunctionalInterface
public interface FunctionThatThrows<T, R> {
R apply(T t) throws Exception;
}
public void perform() {
try {
unchecked((String x) -> Integer.parseInt(x)).apply("abc");
} catch (Exception e) {
System.out.println("Encountered exception" + e.getMessage());
}
}
public void perform1() {
try {
unchecked(<fill-in-here-using-method-reference>);
} catch (Exception e) {
System.out.println("Encountered Exception" + e.getMessage());
}
}
public <T, R> Function<T, R> unchecked(FunctionThatThrows<T, R> f) {
return (a) -> {
try {
return f.apply(a);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
public static void main(String[] args) {
FunctionalInterfaceTest test = new FunctionalInterfaceTest();
test.perform();
test.perform1();
}
}
I want to use Method Reference in the perform1 method to get similar result as in the perform method. I tried using a method reference like Integer::parseInt in perform1 but it doesnt work. How do I do the same with a method reference and why is the method reference giving an error?
unchecked((FunctionThatThrows<String, Integer>) Integer::parseInt).apply("abc")? and that didn't work which way?parseIntare there that can potentially match yourInteger::parseInt? When you cast, you explicitly say to the compiler whichparseIntto useFunction<String,Integer> f = unchecked(Integer::parseInt);...