munHunger
munHunger

Reputation: 2999

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?

Upvotes: 2

Views: 49

Answers (1)

Khalid Shah
Khalid Shah

Reputation: 3232

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.

Upvotes: 2

Related Questions