简体   繁体   English

Lambda表达式中的Java代码是什么意思?

[英]What does this Java code in Lambda expression mean?

Handler handler = new Handler(Looper.getMainLooper() );
Runnable workRunnable;
@Override public void afterTextChanged(Editable s) {
    handler.removeCallbacks(workRunnable);
    workRunnable = () -> search(s.toString());
    handler.postDelayed(workRunnable, 500 /*delay*/);
}

what does this expression mean? 这个表达是什么意思?

workRunnable = () -> search(s.toString());

In normal Java code how is it written in? 在普通的Java代码中,它是如何编写的?

Doing this: 这样做:

workRunnable = () -> search(s.toString());

is the same as doing: 与执行相同:

workRunnable = new Runnable() {
    @Override
    public void run() {
        search(s.toString());
    }
};

Actually, low-level implementation is different and lambdas aren't just syntactic sugar added by the compiler, ie they are not internally translated to anonymous inner classes. 实际上,低级实现是不同的,lambda不仅仅是编译器添加的语法糖,即,它们未在内部转换为匿名内部类。 Nevertheless, when anonymous inner classes extend a functional interface (an interface that has only one abstract method), both mean almost the same, from a semantic point of view. 但是,当匿名内部类扩展功能接口 (只有一种抽象方法的接口)时,从语义的角度来看,两者的含义几乎相同。

One difference is that within an anonymous inner class, if you refer to this , you will be referencing the instance of the anonymous inner class, while within a lambda, if you refer to this , you will be referencing the instance of the enclosing class where the lambda is defined. 一个区别是,在匿名内部类中,如果引用this ,则将引用匿名内部类的实例;而在lambda中,如果引用this ,则将引用封闭的类的实例,其中lambda已定义。

You might want to read the lesson about lambdas in The Java Tutorial , which explains lambdas and how to use them. 您可能想阅读The Java Tutorial中有关lambda的课程 ,其中解释了lambda及其使用方法。

Lambdas are anonymous implementations of single method interfaces. Lambda是单方法接口的匿名实现。 They can be any single method interface, but built-in ones include: 它们可以是任何单一方法接口,但内置的接口包括:

() -> doSomethingButDonTReturnAnything()  // Runnable
() -> returnV() // Supplier<V>
x -> doSomethingWithXButDontRetunAnything(x) // Consumer<K>
x -> returnVFromX(x) // Function<K,V>
(x, y) -> doSomethingWithXAndYButDontReturnAnything(x,y) // BiConsumer<K,V>
(x, y) -> doSomethingWithXAndYAndReturnM(x, y) // BiFunction<K,V,M>

() just means there are no input parameters. ()仅表示没有输入参数。 There are also Primitive versions like IntFunction and Predicate. 也有诸如IntFunction和Predicate之类的原始版本。 Any code that implements the required interface can be used inside the lambda, ie Function for Stream::map can be anything that takes K and returns V. One limitation is that the built-in interfaces don't throw exceptions, so you have to roll your own interfaces if you want to use lambdas that throw exceptions. 任何实现所需接口的代码都可以在lambda内使用,即Stream :: map的函数可以是带K并返回V的任何东西。一个限制是内置接口不会引发异常,因此您必须如果要使用引发异常的lambda,请滚动自己的接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM