Java Lambdas可以有状态吗? [英] Can Java Lambdas have state?

查看:43
本文介绍了Java Lambdas可以有状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在有关lambda和匿名类之间差异的争论之一中,这篇文章:

In one of the arguments about differences between lambdas and anonymous classes, in this post:

Java8 Lambdas与匿名类

我读到一个宣称"Lambda可以具有状态"的说法,就像匿名类实例一样.

I read a claim that "Lambdas can have state" just like anonymous class instances.

据我所知,您无法添加仅属于lambda的用户定义状态,因为无法在Java lambda函数的实现上定义实例成员.

As far as I know, you cannot add user defined state that belongs exclusively to the lambda , since there is no way to define instance members on an implementation of a java lambda function.

例如:

Runnable r=  () -> { int x = 5;  }; // defines a local - no way to define instance
Runnable r2 = new Runnable() {
    int x;  // defines state via instance member
    @Override
    public void run() {
        // TODO Auto-generated method stub

    }
};

请澄清一下,我并不是想将状态引入lambda,因为我认为这与意图背道而驰.我只是想验证或反驳由信誉卓著的人士在上述堆栈溢出问题上提出的技术性主张.

Just to clarify, I am not trying to introduce state to a lambda, as I think that goes against the intent. I am just trying to verify or disprove a claim of a technical nature that was made by a reputable source on the above stack overflow question.

推荐答案

尽管lambda函数没有实例变量之类的东西,但它可以更新某些状态.根据您对此的看法,您可以说lambda函数具有其自己的状态.

Although the lambda function does not have anything like instance variables, it can update some state. Depending on how you regard this, you could say that the lambda function has its own state.

例如

Supplier<Integer> makeCountingLambda() {
    final int[] counter = new int[1];
    return (() -> ++counter[0]);
}

Supplier<Integer> f = makeCountingLambda();
f.get(); // 1
f.get(); // 2

f是lambda函数.每次调用get()时,它将提供一个新值,因为它的状态已更新.

f is a lambda function. It will supply a new value each time get() is called, because its state is updated.

类似的东西似乎就是引用的评论所描述的.

Something like this seems to be what the referenced comment was describing.

这篇关于Java Lambdas可以有状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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