usr-local-ΕΨΗΕΛΩΝ
usr-local-ΕΨΗΕΛΩΝ

Reputation: 26894

How do I build a lambda-based fluent builder?

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 Consumers of the type of the target property.

So how do I build my own fluent Optional?

Upvotes: 1

Views: 168

Answers (1)

usr-local-ΕΨΗΕΛΩΝ
usr-local-ΕΨΗΕΛΩΝ

Reputation: 26894

After little research I found that setters are just BiConsumers 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

Related Questions