lambda with non-static methods in Java 8

后端 未结 1 1721
一生所求
一生所求 2020-12-10 05:54

I am trying to learnd lambdas in new Java 8. There is one interesting thing. If method has the same signature as functional interface, it can be assigned to it using lambdas

相关标签:
1条回答
  • 2020-12-10 06:36

    This is because lambdas are not from Object Oriented world.

    When you assign some method to Comparator<Integer> it's task is to perform the comparision.

    Comparator<Integer> methodOne = Integer::compare;
    Comparator<Integer> methodTwo = Integer::compareTo;
    

    This methodOne.compare(1,2); will be translated to Integer.compare(1,2) it is called non-instance-capturing and refer to static method

    This methodTwo.compare(1,2); will be translated to 1.compareTo(2) is is called instance-capturing and refers to instance methods.

    Compiler "knows" what type of method you have referenced so it can process without error.

    Method reference capture

    0 讨论(0)
提交回复
热议问题