Writing an incremental integer provider
I am trying to get some grip on functional programming in Java 8. I tried to write the following IntSupplier
"functional", but I keep getting problems.
import java.util.function.IntSupplier;
@Test public void test_nonFunctional() {
IntSupplier supplier = new IntSupplier() {
private int nextInt = 0;
@Override public int getAsInt() {
return nextInt++;
}
};
}
Here are my attempts. Problems are marked as comments in the code.
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 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.
}
}
If the answer is simply that it cannot be accomplished without the use of additional objects, just say so.
+3
source to share
1 answer
Your problem definition doesn't work anymore. In functionality, you cannot have other output without an argument. This is the definition. But how to create a sequence of numbers, which you can see in the java-libraries: java.util.function.IntUnaryOperator
. It is used as follows:
IntStream.iterate(0, i -> i+1).limit(10).foreach(System.out::printLn);
+2
source to share