Search code examples
javagenericscastingtype-parameter

Returning generic object from function


I am writing a function for adding metrics to our service and I want to make it generic so that it can be used for different types of metrics. I don't want to do any weird casting so I thought of just making the function generic like this:

public <T extends Metric> T addMetric(String key,
        Function<MetricRegistry, T> metricProducer) {
    MetricRegistry registry = SharedMetricRegistries.tryGetDefault();

    Metric m = metricProducer.apply(registry);
    registry.register(key, m);

    return m;
}

However it won't work because of "incompatible types" which I find quite odd. It states that it requires T but found Metric on the return, but isn't T already defined as a Metric acording to the type parameter?


Solution

  • Change

    public <T extends Metric> T addMetric(String key,
            Function<MetricRegistry, T> metricProducer)
    

    To

    public <T extends Metric> Metric addMetric(String key,Function<MetricRegistry, T> metricProducer)
    

    Or Change

    Metric m = metricProducer.apply(registry);
    

    To

    T m = metricProducer.apply(registry);
    

    Both will work.