A warehouse constructor that takes a parameter in a link

I have a class

public class Person { private int age; } 

And using Supplier in java 8, I can save the link to the constructor, for example

 Supplier<Person> personSupplier = Person::new 

But what if my constructor accepts the age parameter as

 public class Person { private int age; public Person(int age) {this.age = age;} } 

Now

 Supplier<Person> personSupplier = Person::new 

doesn't work, so what should be the correct signature for personSupplier ? Obviously, I can do something like.

 Supplier<Person> personSupplier = () -> new Person(10); 

But for each person, age must be different, so he does not solve my problem.

Maybe I should use something else instead of Supplier ?

+6
source share
2 answers

You can use java.util.function.Function in Java and set age when calling apply .

eg.

 Function<Integer, Person> personSupplier = Person::new; Person p1 = personSupplier.apply(10); Person p2 = personSupplier.apply(20); 

Which is equivalent

 Function<Integer, Person> personSupplier = (age) -> new Person(age); Person p1 = personSupplier.apply(10); Person p2 = personSupplier.apply(20); 
+7
source

So what should be the correct signature for personSupplier ?

It will be Function<Integer, Person> or IntFunction<Person> .

You can use it as follows:

 IntFunction<Person> personSupplier = Person::new; Person p = personSupplier.apply(10); // Give 10 as age argument 

Subsequent:

What if I have Person(String name, int age) ?

You can use BiFunction<String, Integer, Person> in the same way as described above.


Follow-up observation # 2:

What if I have Person(String firstName, String lastName, int age) ?

You will not find a suitable type in the API. You will need to create your own interface as follows:

 @FunctionalInterface interface PersonSupplier { Person supplyPerson(String firstName, String lastName, int age); } 

This could be used in the same way:

 PersonSupplier personSupplier = Person::new; // Assuming a Person has a name Person p = personSupplier.supplyPerson("peter", "bo", 10); 
+5
source

Source: https://habr.com/ru/post/988186/


All Articles