Lambda in Java works in conjunction with the concept of a functional interface .
A typical example is Function . Function - a functional interface whose functional method apply is a method that takes one argument and returns the result.
You can create your own functional interface that defines a functional method with 4 parameters and without a return type, for example:
@FunctionalInterface interface RectangleDrawer { void draw(double x, double y, double w, double h); }
( FunctionalInterface annotation is not strictly necessary, but gives clear intent).
Then you can create a lambda that matches the contract of this functional interface. Typical lambda syntax is (method arguments) -> (lambda body) . In this example, it will be: (x, y, w, h) -> gc.fillRect(x, y, w, h) . This compiles because the lambda declares 4 arguments and does not have a return type, so it can be represented as the RectangleDrawer function method defined earlier.
Example:
static GraphicsContext gc; public static void main(String[] args) { draw(0, 0, 50, 50, (x, y, w, h) -> gc.fillRect(x, y, w, h)); draw(0, 0, 50, 50, (x, y, w, h) -> gc.strokeRect(x, y, w, h)); } static void draw(double x, double y, double w, double h, RectangleDrawer drawer) { drawer.draw(x, y, w, h); }
In this particular case, you can use the link to create a lambda using the :: operator, which allows you to write simpler code:
static GraphicsContext gc; public static void main(String[] args) { draw(0, 0, 50, 50, gc::fillRect); draw(0, 0, 50, 50, gc::strokeRect); } static void draw(double x, double y, double w, double h, RectangleDrawer drawer) { drawer.draw(x, y, w, h); }