1

In Sonarcube I am getting an error to convert the following code to Lambda but facing difficulty.

private MeterFilter getDefualtConfig() {
        return new MeterFilter() {
            @Override
            public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) {
                return DistributionStatisticConfig.builder().percentilesHistogram(true).percentiles(0.95, 0.99, .5)
                        .build().merge(config);
            }
        };
    }
Ravat Tailor
  • 1,193
  • 3
  • 20
  • 44
  • OK. What is your question? What have you tried? What difficulty are you facing? Have you read tutorials, documentation about lambdas? – JB Nizet Jul 14 '18 at 18:48
  • @JBNizet, I was trying return (Meter.Id id, DistributionStatisticConfig config) -> DistributionStatisticConfig.builder().percentilesHistogram(true).percentiles(0.95, 0.99, .5).build().merge(config); and getting the error target of this interface must be functional interface – Ravat Tailor Jul 14 '18 at 18:56
  • How is MeterFilter defined? Is it an interface or a class? If it's a class, then SonarKube has a bug: you can't use a lambda to define an instance of a class. If it's an interface, your code should compile. – JB Nizet Jul 14 '18 at 19:02
  • It is an interface but when I look to its code it is all the methods are static and default but no abstract method – Ravat Tailor Jul 14 '18 at 19:08
  • Then you can't use a lambda to override it. You can only implement a functional interface using a lamda, i.e. an interface defining one and only one abstract method. – JB Nizet Jul 14 '18 at 19:09
  • Ok, Now I got it, Thanks. It seems like Sonar issue – Ravat Tailor Jul 14 '18 at 19:11
  • Does this answer your question? [how to replace anonymous with lambda in java](https://stackoverflow.com/questions/37695456/how-to-replace-anonymous-with-lambda-in-java) – s.d Sep 15 '20 at 19:25

1 Answers1

1

The lambda equivalent would be:

return (id, config) -> DistributionStatisticConfig.builder()
                               .percentilesHistogram(true)
                               .percentiles(0.95, 0.99, .5)
                               .build()
                               .merge(config); 
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • correct, similar way I was trying to do this but getting an error. target of this interface must be functional interface – Ravat Tailor Jul 14 '18 at 18:58
  • @RavatTailor you can only convert the aforementioned code to a lambda if `MeterFilter` is a functional interface i.e. an interface with a SAM. if `MeterFilter` is indeed a functional interface and yet you're still getting the error that you can convert the code to a lambda then there is most likely a bug Sonarcube. – Ousmane D. Jul 14 '18 at 19:00
  • 1
    Hey Thanks for the answer, Metafilter is not a SAM interface, you are right it seems like Sonar Issue – Ravat Tailor Jul 14 '18 at 19:31