Lambdas:局部变量需要final,实例变量不需要 [英] Lambdas: local variables need final, instance variables don't

查看:108
本文介绍了Lambdas:局部变量需要final,实例变量不需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在lambda中,局部变量需要是final,但实例变量不需要。为什么会这样?

In a lambda, local variables need to be final, but instance variables don't. Why so?

推荐答案

字段和局部变量之间的根本区别在于局部变量是 JVM创建lambda实例时复制 。另一方面,字段可以自由更改,因为它们的更改也会传播到外部类实例(它们的范围是整个外部类,正如Boris在下面指出的那样)。

The fundamental difference between a field and a local variable is that the local variable is copied when JVM creates a lambda instance. On the other hand, fields can be changed freely, because the changes to them are propagated to the outside class instance as well (their scope is the whole outside class, as Boris pointed out below).

最简单的思考匿名类,闭包和labmdas的方法是从变量范围的角度来看;想象一下为传递给闭包的所有局部变量添加的复制构造函数。

The easiest way of thinking about anonymous classes, closures and labmdas is from the variable scope perspective; imagine a copy constructor added for all local variables you pass to a closure.

这篇关于Lambdas:局部变量需要final,实例变量不需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆