IntelliJ 和内置 Java 函数接口

我的 Spring 组件实现了 java.util.function.Function。这背后的想法是强制使用带有小封装函数的函数式风格。


@Component

public class MyFunction implements Function<In, Out> {

    public Out apply(In in) { .... }

}


// example usage

@RestController

public class MyApi {

    private MyFunction f;

    public void foo() {

        someList.stream()

            .map(f)

            . // whatever

    }

}

IntelliJ 2018.1 出现两个问题:

  • “查找用法”提供了查找基本方法用法的选项。如果我不小心点击了“是”,IntelliJ 会发现无数的用法并减慢速度,直到它几乎冻结。好吧,我绝对应该在这里选择“否”,但这仍然是一个小问题。

  • 在带有“方法引用”(如 IntelliJ 建议)的 Stream(例如过滤器)中使用该函数甚至更成问题。使用“查找用法”并选择“否”将不会显示我正在寻找的“真实”用法。这使得很难在代码中导航。

这引出了我的问题:使用内置函数接口是一个好习惯还是我应该编写自己的函数而不将其声明为 FunctionalInterface?您是否将上述问题视为 IntelliJ 错误?有你知道的解决方法吗?


泛舟湖上清波郎朗
浏览 122回答 2
2回答

MM们

您的方法对我来说似乎有效,但我尽量避免直接实施Function。主要原因是:命名.我可以理解,如果一个类有一个有意义的名称(例如InOutMapFunction),您可能不会觉得该方法也需要一个有意义的名称。不过,我更喜欢的名字InOutMapper.mapInToOut来InOutMapFunction.apply。另外,如果你能想到的不止一个InOutMapper,那就让它成为一个接口,让组件来实现它。有些人可能认为,如果它们与现有的接口“对应”,那么创建自己的功能接口是不值得的,但我几乎从不后悔,尤其是在实际用例中,这会极大地影响可读性,例如比较:SomeParticularTypeContextFinder, 和Function<SomeParticularType, SomeParticularTypeContext>.这是我如何实施您的示例:@Componentpublic class PlainInOutMapper implements InOutMapper {&nbsp; &nbsp; @Override&nbsp; &nbsp; public Out mapInToOut(In in) { .... }}@FunctionalInterfaceinterface InOutMapper {&nbsp; &nbsp; Out mapInToOut(In in);}// example usage@RestControllerpublic class MyApi {&nbsp; &nbsp; private List<In> someList;&nbsp; &nbsp; private InOutMapper mapper;&nbsp; &nbsp; public void foo() {&nbsp; &nbsp; &nbsp; &nbsp; someList.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(mapper::mapInToOut)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . // whatever&nbsp; &nbsp; }}

慕仙森

您可以通过“查找用法设置”限制搜索范围(Windows 上的默认设置:CTRL+ALT+SHFT+F7)这些设置适用于通过 ALT+F7 以及鼠标滚轮单击的搜索。也许将其限制为您当前的模块可以解决问题?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java