search

Home  >  Q&A  >  body text

java8中的lambda定义的函数该如何引用

定义好的函数,不知道该如何使用。

// 不知道怎么引用
BinaryOperator<Long> add = (x, y) -> x + y;
PHP中文网PHP中文网2812 days ago329

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:20:55

    public class Main {
        
        private long t, u;
        
        private Long test(BinaryOperator<Long> b) {
            return b.apply(t, u);
        }
        public static void main(String[] args) {
            
            Main m = new Main();
            m.t = 1; m.u = 2;
            BinaryOperator<Long> b = (x, y) -> x + y;
            System.out.println(m.test(b));
        }
    }

    It is useless to pull it out alone. Lambda only defines the operation method of data, that is, it defines a function. Specifically where to use it, you need to define a method with a lambda expression (functional interface) as the parameter, and then call the actual operation of lambda (which function in the interface definition) inside the method, such as accept.

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 09:20:55

    Lambda定义的并不是函数,它只是匿名类的缩写方式,其生成的还是一个对象。就如你的例子中,它生成的一个BinaryOperator<Long>Object, then it is an instance object of this class. How to use it is the same as how to use an object.

    reply
    0
  • Cancelreply