Java 8 Supplier with arguments in the constructor

cahen picture cahen · Jul 6, 2015 · Viewed 89.6k times · Source

Why do suppliers only support no-arg constructors?

If the default constructor is present, I can do this:

create(Foo::new)

But if the only constructor takes a String, I have to do this:

create(() -> new Foo("hello"))

Answer

Brian Goetz picture Brian Goetz · Jul 7, 2015

But, a 1-arg constructor for T that takes a String is compatible with Function<String,T>:

Function<String, Foo> fooSupplier = Foo::new;

Which constructor is selected is treated as an overload selection problem, based on the shape of the target type.