java编写增量整数供应商
我试图掌握一些Java 8函数式编程。我试图“从功能上”写下面的IntSupplier
,但我一直遇到问题
import java.util.function.IntSupplier;
@Test public void test_nonFunctional() {
IntSupplier supplier = new IntSupplier() {
private int nextInt = 0;
@Override public int getAsInt() {
return nextInt++;
}
};
}
以下是我的尝试。这些问题在代码中标记为注释
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntSupplier;
public class IntSupplierTest {
@Test public void test_nonFunctional() {
IntSupplier supplier = new IntSupplier() {
private int nextInt = 0;
@Override public int getAsInt() { return nextInt++; }
}; // Works but is not functional.
}
@Test public void test_naive() {
int nextInt = 0;
IntSupplier supplier = () -> nextInt++; // Doesn't compile: requires nextInt to be final.
}
@Test public void test_nextIntIsFinal() {
final int nextInt = 0;
IntSupplier supplier = () -> nextInt++; // Doesn't compile: nextInt can't be incremented because it's final.
}
@Test public void test_useWrapper() {
final AtomicInteger nextInt = new AtomicInteger(0);
IntSupplier supplier = () -> nextInt.getAndIncrement(); // It is not the same as my original question as this test uses an extra object.
}
}
如果答案很简单,不使用额外的对象就无法完成,请直接说出来
# 1 楼答案
你可以这样做: