1

I created this GenericBuilder class (barely inspired by How to implement the builder pattern in Java 8?)

public class GenericBuilder<T> {

    private final T instance;

    private GenericBuilder(T instance) {
        this.instance = instance;
    }

    public static <T> GenericBuilder<T> of(Supplier<T> instantiator) {
        return new GenericBuilder<T>(instantiator.get());
    }

    public <U> GenericBuilder<T> with(BiConsumer<T, U> consumer,
                                      U value) {
        ((Consumer<T>) t -> consumer.accept(t, value)).accept(instance);
        return this;
    }

    public <U> GenericBuilder<T> with(BiConsumer<T, U> consumer,
                                      Supplier<U> supplier) {
        return with(consumer, supplier.get());
    }

    public T build() {
        return instance;
    }
}

But the second with() method throws

incompatible types: cannot infer type-variable(s) U (argument mismatch; java.lang.Long is not a functional interface)

when I execute the following:

GenericBuilder.of(Dto::new)
        .with(Dto::setId, entity::getId)
        .build();

Notice that entity is an instance of an Entity class.

Rohan Grover
  • 1,514
  • 2
  • 17
  • 23
user1919662
  • 61
  • 1
  • 3
  • could you provide some sample data to reproduce the said error with? – Ousmane D. Dec 28 '18 at 22:31
  • 2
    I may just be missing something, but why can't `with` be implemented as just `consumer.accept(instance, value)`? Why declare a separate lambda if you're just going to immediately invoke it? – Daniel Pryden Dec 28 '18 at 22:32
  • What version of Java are you compiling with? – Jacob G. Dec 28 '18 at 22:39
  • Daniel, you are right, thanks for advice but the error remains. Jacob, java version "1.8.0_152". – user1919662 Dec 28 '18 at 22:41
  • Can you try updating to a later version of Java (preferably 11) and tell us if the error persists? There have been many inference improvements in later versions. – Jacob G. Dec 28 '18 at 22:44
  • With type erasure I imagine overloading ```with()``` is problematic. Have you tried with just the ```with(BiConsumer, Supplier)``` variant present? – d.j.brown Dec 28 '18 at 22:47

0 Answers0