Java Reference
In-Depth Information
You can rewrite these statements by replacing the lambda expressions with constructor references as shown:
Supplier<String> func1 =
String::new
;
Function<String,String> func2 =
String::new
;
The syntax for using a constructor is
ClassName::new
ArrayTypeName::new
The
ClassName
in
ClassName::new
is the name of the class that can be instantiated; it cannot be the name of an
abstract class. The keyword
new
refers to the constructor of the class. A class may have multiple constructors. The
syntax does not provide a way to refer to a specific constructor. The compiler selects a specific constructor based
on the context. It looks at the target type and the number of arguments in the abstract method of the target type.
The constructor whose number of arguments matches with the number of arguments in the abstract method of the
target type is chosen. Consider the following snippet of code that uses three constructors of the
Item
class, shown in
Listing 5-16, in lambda expressions:
Supplier<Item> func1 =
() -> new Item()
;
Function<String,Item> func2 =
name -> new Item(name)
;
BiFunction<String,Double, Item> func3 =
(name, price) -> new Item(name, price)
;
System.out.println(func1.get());
System.out.println(func2.apply("Apple"));
System.out.println(func3.apply("Apple", 0.75));
Constructor Item() called.
name = Unknown, price = 0.0
Constructor Item(String) called.
name = Apple, price = 0.0
Constructor Item(String, double) called.
name = Apple, price = 0.75
The following snippet of code replaces the lambda expressions with a constructor reference
Item::new
.
The output shows the same constructors are used as before.
Supplier<Item> func1 =
Item::new
;
Function<String,Item> func2 =
Item::new
;
BiFunction<String,Double, Item> func3 =
Item::new
;
System.out.println(func1.get());
System.out.println(func2.apply("Apple"));
System.out.println(func3.apply("Apple", 0.75));
Constructor Item() called.
name = Unknown, price = 0.0
Constructor Item(String) called.
name = Apple, price = 0.0
Constructor Item(String, double) called.
name = Apple, price = 0.75