I know that I can pass a reference of a method to another method, like this:
foo(Bar::doBar); // or e.g.
foo(bar::doBar); // or e.g.
foo(this::doBar);
Is it possible to pass a reference to new operator?
Android studio says that I ought to replace a line like this:
(a, b) -> new Pair<>(a, b)
with a method reference to new. But how do I do that?
A constructor reference is a special case of a Method Reference Expression. As a small point of terminology, the reference is not to the operator, but to a particular constructor. If, for instance, Pair<T> had more than one constructor, the right one would be selected based on the static context.
Different ways to refer to a constructor (from JLS):
ArrayList<String>::new // constructor for parameterized type
ArrayList::new // inferred type arguments
// for generic class
Foo::<Integer>new // explicit type arguments
// for generic constructor
Bar<String>::<Integer>new // generic class, generic constructor
int[]::new // array creation
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