Instance Method Reference and Lambda Parameters

前端 未结 2 1718
抹茶落季
抹茶落季 2020-11-27 21:44

I am having trouble understanding the syntax for a method reference, where there are two parameters a and b, and the reference is to a method of

2条回答
  •  攒了一身酷
    2020-11-27 22:35

    I would give a couple of examples here, for those who find Oracle documentation a bit hard to take in. Imagine you need a reference to a Comparator instance:

    .sorted(String::compareTo)
    

    String::compareTo is identical to:

    (String a, String b) -> a.compareTo(b);
    

    Because, as Jon explained, a method reference will be transformed to a lambda that will expect 2 parameters. The actual arbitrary object passed in the stream as a first argument, and one more parameter(since Comparator expects int compare(T o1, T o2)). Another case:

    .map(Employee::getSalary)
    

    In this case map expects: Function. Function requires implementation of R apply(T var1) - a method with 1 argument. In this case the only parameter that will be passed to the lambda is the actual arbitrary object - instance on Employee.

    To sum up - depending on the compile time context, method reference to arbitrary object will always be "transformed" into a lambda that expects that object as a first parameter + any number of parameters that the target method requires in the same corresponding order.

提交回复
热议问题