1

Given the following builder setup:

class Factory {
    public static <T> FooBuilder<T> fooBuilder() {
        return new FooBuilder<>();
    }
}

class FooBuilder<T> {

    int x;

    public FooBuilder<T> addFooStep(int x) {
        this.x = x;
        return this;
    }

    public Metric<T> build() {
        return new Metric<>(x);
    }
}

class Metric<T> {

    final int cm;

    public Metric(int cm)
    {
        this.cm = cm;
    }
}

Somewhere the type T information is lost. So in order to use this builder, I have to specify the type explicitly like:

Metric<Integer> integerMetric = Factory.<Integer>fooBuilder()
            .addFooStep(1)
            .build();

However, I would like to be able to use it without the explicity type notation, like:

Metric<Integer> integerMetric = Factory.fooBuilder()
            .addFooStep(1)
            .build();

Is this possible, and if so, how can it be achieved?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
SnowmanXL
  • 724
  • 5
  • 14
  • The compiler doesn't carry inferred types across a chain of generic method calls like that. It's a known limitation. Check [Why does Java generics type inference break in chained method calls?](https://stackoverflow.com/questions/66089702/why-does-java-generics-type-inference-break-in-chained-method-calls) – ernest_k Nov 23 '21 at 12:35

0 Answers0