I am looking at the lambda and javaFX sample project "MaryHadALittleLambda" (https://github.com/steveonjava/MaryHadALittleLambda).
Everything compiles fine except the method
private void populateCells(Group root, final SpriteView.Mary mary) {
// Gratuitous use of lambdas to do nested iteration!
Group cells = new Group();
IntStream.range(0, HORIZONTAL_CELLS).mapToObj(i ->
Rectangle rect = new Rectangle(i * CELL_SIZE, j * CELL_SIZE, CELL_SIZE, CELL_SIZE);
rect.setFill(Color.rgb(0, 0, 0, 0));
rect.setStrokeType(StrokeType.INSIDE);
rect.setStroke(Color.BLACK);
rect.setOnMousePressed(e -> mary.moveTo(new Location(i, j)));
return rect;
})
).flatMap(s -> s).forEach(cells.getChildren()::add); // <-- ERROR HERE
root.getChildren().add(cells);
}
as I get an error in Eclipse on the forEach line,
The type ObservableList<Node> does not define add(Object) that is applicable here
The forEach takes a method reference to an instance method of the cells object, which looks perfectly valid to me. If I use the following lambda instead, it works fine :
).flatMap(s -> s).forEach(r -> cells.getChildren().add((Rectangle) r));
So it seems that every features of java 1.8 are compiling safe for this javaFx reference. My guess is that something is wrong with my version or setup of Java? I am using :
Eclipse Standard/SDK version: Kepler Service Release 2
Eclipse Java Development Tools Patch with Java 8 support (for Kepler SR2)
And using the JRE from this Java version (output from the command line) :
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
Thanks.
I will be answering my own question by providing some updates: I contacted the author who suggested I try the java compiler, not eclipse's: building with Ant (and hence using the jdk javac compiler) compiles just fine, and the application runs.
When I looked at the status of java 8 support in eclipse, it seems there are many things to be resolved : https://bugs.eclipse.org/bugs/buglist.cgi?quicksearch=1.8%20lambda
As @jewelsea pointed, Intellij Idea shows the error but will compile and execute (I assume it uses the jdk-provided javac).
So the answer is : wait for upcoming updates to eclipse and/or the jdk. This specific case is easy to work-around.
And the real issue is that mapToObj provides a Stream<Object>, and the loop will pass Object to the ::add which expects Nodeinstances (as Rectangle are).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With