저는 Java 8 함수 프로그래밍에 대해 몇 가지 이해하려고합니다. 나는 "functionalally"다음의 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.
}
}
답변이 단순히 추가 물체를 사용하지 않고는 불가능하다는 이유만으로 말하십시오.
는 –