声纳:用方法参考替换这个lambda [英] Sonar : Replace this lambda with a method reference

查看:540
本文介绍了声纳:用方法参考替换这个lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码示例

Collection<Number> values = transform(
        getValuatedObjects(),
        input -> getValueProvider().apply(input).getValue());

违反 sonarqube规则


尽可能用方法引用替换lambdas

Replace lambdas with method references when possible

它是声纳虫吗?
或者我真的可以使用方法参考吗?

is it a sonar bug ? or can i really use a method reference ?

推荐答案

你无法替换lambda 输入 - > getValueProvider()。apply(input).getValue()使用方法引用而不更改语义。

You can’t replace the lambda input -> getValueProvider().apply(input).getValue() with a method reference without changing the semantics.

方法引用替换单个方法调用,因此它不能简单地替换由多个方法调用组成的lambda表达式。

A method reference replace a single method invocation, so it can’t simply replace a lambda expression consisting of more than one method invocation.

形式为<$的lambda表达式c $ c>输入 - > getValueProvider()。apply(输入)可以替换为 getValueProvider():: apply 当且仅当评估时间<$时c $ c> getValueProvider()无关紧要,因为在lambda形式中,在每个lambda body评估时调用该方法,而对于方法引用,它只被调用一次并捕获结果。

A lambda expression of the form input -> getValueProvider().apply(input) could be replaced by getValueProvider()::apply if, and only if, the evaluation time of getValueProvider() does not matter as in the lambda form the method is invoked on each lambda body evaluation while for the method reference it is invoked only once and the result captured.

这类似于 x - >之间的差异。 System.out.println(x) System.out :: println 其中读取字段 System的内容。 out 在不同时间发生,但通常无关紧要。但是你应该知道区别。

This is similar to the difference between x -> System.out.println(x) and System.out::println where reading the contents of the field System.out happens at different times but usually it doesn’t matter. But you should be aware of the difference.

在你的例子中,调用了第三种方法 getValue()。使用方法引用表达它的唯一方法是需要一个功能接口,如 Function ,其中包含和then 等方法和/或组成。但是,Java 8的工作方式,需要将第一个方法引用转换为目标接口来调用组合方法,这种组合方法现在更容易读取你现有的lambda表达式:((函数< X,Y>)getValueProvider():: apply).andThen(Y :: getValue)其中 Y 是类型, apply(输入)返回。

In your example, a third method getValue() is invoked. The only way to express that with method references needs a functional interface like Function which has methods like andThen and/or compose. However, the way Java 8 works, that would require casting the first method reference to the target interface to invoke the combining method which would be by no way easier to read that the lambda expression you have now: ((Function<X,Y>)getValueProvider()::apply).andThen(Y::getValue) where Y is the type, apply(input) returns.

请注意,规则说在可能的情况下用方法引用替换lambda 这给你空间说,好吧,这里不可能,但是,我不确定你能把它称为规则那么多......

Note that the rule says "Replace lambdas with method references when possible" which gives you room to say, "well, here it is impossible", however, I’m not sure how much you can call it a "rule" then…

这篇关于声纳:用方法参考替换这个lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆