Returning generic object from function

munHunger :

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?

Khalid Shah :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=150177&siteId=1