Reputation: 26894
I would like to create a Java fluent builder that is based on java.util.Optional
to simplify my life
I would like to be able to call it like:
Person person = Optional.supply(Person::new)
.with(Person::setName,"Andrew")
.with(Person::setAge,32)
.with(Person::setAddress,"10 Downing Street")
.get();
In my example, I have called my new class Optional exactly as the original. In fact I copied its source code being unable to extend Optional.
I could implement the constructor
public static <T> Optional<T> supply(Supplier<T> supplier)
{
T value = requireNonNull(supplier).get();
return new Optional<T>(value);
}
But then I don't know how to implement the fluent setter. It should allow me setting a value in the held entity and return the optional self.
Setters are Consumer
s of the type of the target property.
So how do I build my own fluent Optional?
Upvotes: 1
Views: 168
Reputation: 26894
After little research I found that setters are just BiConsumer
s of T and V where T is the entity type and V is the property type.
Whoever wants to build a fluent optional setter can use
public <H> Optional<T> with(BiConsumer<T, H> setter, H value)
{
requireNonNull(setter);
if (!isPresent())
return empty();
setter.accept(this.value, value);
return this;
}
Sharing for posterity
Upvotes: 1