我的 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 出现两个问题:
- “查找用法”提供了查找基本方法用法的选项。如果我不小心点击"is",IntelliJ 会发现无数的用法并减慢速度,直到几乎卡住。好吧,我绝对应该在这里选择“否”,但这仍然是一个小问题。
- 通过“方法引用”(如 IntelliJ 建议)使用流中的函数(例如过滤器)会出现更多问题。使用“查找用法”并选择“否”将不会显示我正在寻找的“真实”用法。这使得在代码中导航变得困难。
这引出了我的问题:使用内置函数接口(interface)是一个好的做法还是我应该编写自己的函数而不将其声明为函数接口(interface)?您是否认为上述问题是 IntelliJ 的 bug?您知道有解决方法吗?
最佳答案
你的方法对我来说似乎有效,但我尽量避免直接实现 Function
越多越好。主要原因是:命名。
我可以理解,如果一个类有一个有意义的名称(例如 InOutMapFunction
),您可能不需要该方法也有一个有意义的名称。不过,我更喜欢像InOutMapper.mapInToOut
这样的名字。至InOutMapFunction.apply
.
此外,如果你能想到多个InOutMapper
,将其设为接口(interface)并让组件实现它。
有些人可能认为,如果它们与现有的功能接口(interface)“对应”,那么创建自己的功能接口(interface)是不值得的,但我几乎不会后悔,特别是在实际用例中,这会极大地影响可读性,例如比较:
-
SomeParticularTypeContextFinder
,并且 -
Function<SomeParticularType, SomeParticularTypeContext>
.
以下是我实现您的示例的方法:
@Component
public class PlainInOutMapper implements InOutMapper {
@Override
public Out mapInToOut(In in) { .... }
}
@FunctionalInterface
interface InOutMapper {
Out mapInToOut(In in);
}
// example usage
@RestController
public class MyApi {
private List<In> someList;
private InOutMapper mapper;
public void foo() {
someList.stream()
.map(mapper::mapInToOut)
. // whatever
}
}
关于java - IntelliJ 和内置 Java 函数接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53184684/