Java 8: Lambda with variable arguments

前端 未结 6 1782
天命终不由人
天命终不由人 2021-01-04 02:27

I am looking for a way to invoke multiple argument methods but using a lambda construct. In the documentation it is said that lambda is only usable

6条回答
  •  隐瞒了意图╮
    2021-01-04 02:44

    Yes

    You do not need helper methods, multiple interfaces, or any other baggage.

    However, since Java varargs are implemented using implicit arrays, your lambda will take a single array argument, and have to handle unpacking the argument array.

    You will also have to handle type conversions if your function has arguments that are not all of the same class, with all the inherent danger that entails.

    Example

    package example;
    import java.util.Arrays;
    import java.util.List;
    
    public class Main {
        @FunctionalInterface
        public interface Invoker {
            R invoke(T... args);
        }
    
        @SafeVarargs
        public static  void test(Invoker invoker, T...args) {
            System.out.println("Test result: " + invoker.invoke(args).toString());
        }
    
        public static Double divide(Integer a, Integer b) {
            return a / (double)b;
        }
    
        public static String heterogeneousFunc(Double a, Boolean b, List c) {
            return a.toString() + " " + b.hashCode() + " " + c.size();
        }
        public static void main(String[] args) {
            Invoker invoker = argArray -> Main.divide(argArray[0], argArray[1]);
            test(invoker, 22, 7);
    
            Invoker weirdInvoker = argArray -> heterogeneousFunc(
                    (Double) argArray[0], (Boolean) argArray[1], (List) argArray[2]);
    
            test(weirdInvoker, 1.23456d, Boolean.TRUE, Arrays.asList("a", "b", "c", "d"));
    
            test(weirdInvoker, Boolean.FALSE, Arrays.asList(1, 2, 3), 9.999999d);
        }
    }
    
    

    Output:

    Test result: 3.142857142857143
    Test result: 1.23456 1231 4
    Exception in thread "main" java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Double
        at example.Main.lambda$main$1(Main.java:27)
        at example.Main.test(Main.java:13)
        at example.Main.main(Main.java:32)
    

提交回复
热议问题