开发者社区> 问答> 正文

jdk8 lambda 修改了外部变量值是否为bug?报错

源代码如下(使用jdk8):

@FunctionalInterface
public interface Base<T> {
	/**
	 * 获取对象
	 * @return 对象
	 */
	T get();
}
@FunctionalInterface
public interface BaseFactory<T> {
	/**
	 * 创建新的值
	 * @return 新的值
	 */
	Base<T> create();
}
public interface Key<K> extends Base<K> {}
@FunctionalInterface
public interface KeyFactory<K> extends BaseFactory<K> {
	/**
	 * 创建新的键值
	 * @return 新的键值
	 */
	Key<K> create();
}

以下这个类是一个具体的整型键(Key<Integer>)的创建工厂类:

public class IntegerKeyFactory implements KeyFactory<Integer> {
	
	private int start = 0;
	
	public IntegerKeyFactory() {}
	
	public IntegerKeyFactory(int start) {this.start = start;}

	@Override
	public Key<Integer> create() {
		return () -> start++;
	}
	
	public static void main(String[] args) {
		IntegerKeyFactory factory = new IntegerKeyFactory(1);
		for (int index = 0; index < 10; index++) {
			System.out.println(factory.create().get());
		}
	}

}

执行结果如下:

1
2
3
4
5
6
7
8
9
10

由于想偷懒不写Key<K>接口的实现类,所以在IntegerKeyFactory中用了lambda表达式(return () -> start++;),但等到写完后并且添加了main方法测试后才反应过来:lambda表达式不能访问外部可以被修改的变量(如果变量是引用,引用的地址不能修改),可是因为写好后编译器没有报错,就尝试执行了下,发现可以正确运行,并且这个结果也是我期望的。

有哪位大神能告诉我这是不是个Bug?如果不是Bug,这个原理(lambda表达式修改了外部变量(int类型)的值)是什么?

展开
收起
爱吃鱼的程序员 2020-06-14 20:53:29 529 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    start不是类内的私有属性?怎么成了外部变量?知道了,又学到了一点,类内部变量可以在lambda表达式中使用,区别于外部变量是类内部私有属性啊,但相对于lambda表达式不是外部变量吗?

    2020-06-14 20:53:47
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
《0代码搭应用》 立即下载
不止代码 立即下载
低代码开发师(初级)实战教程 立即下载

相关实验场景

更多