有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

番石榴中有没有类似于功能性Java的效果?

我知道纯函数式编程的目标之一是消除可变性,从而排除副作用。但是,让我们面对现实,Java并不是一种函数式语言,即使存在所有函数式编程库。事实上,一些FP图书馆似乎知道并期待这一点。例如,在函数式Java中,有^{}类。在绝地FP库中,有^{}接口。除其他外,这允许您在不使用讨厌的for循环样板的情况下,将具有类型安全性的命令模式应用于Iterable的元素

Command<PhoneNumber> makeCall = new Command<PhoneNumber> {
    public void execute(PhoneNumber p) { p.call(); }
}
List<PhoneNumber> phoneList = ...
FunctionalPrimitives.forEach( phoneList, makeCall );

所以问题是,番石榴中有类似的东西吗

在回答被接受澄清后编辑

我正在开发一个framework,它可以帮助解决大多数Java FP库在特定情况下固有的“垂直问题”。因此,我将而不是实际制作如上所示的代码示例:即,显式声明Command的一个新类实现及其所有垂直噪声,只是为了在声明之后立即应用它

我考虑的更多是实际的命令模式,可能在其他地方声明了几个可能的命令,其中只有一个被传递到希望迭代应用它的代码中。此外,我的框架的目标是使创建功能接口对象(函数、谓词、命令和其他简单的lambda)更加习惯化,而不只是将垂直问题转移到其他地方。我早就意识到这不在番石榴的范围之内。但由于其他FP库中也有类似命令的接口,我只是想知道番石榴中是否存在类似的接口

使用我的框架,一个更完整的代码示例可能是这样的:

class Stuff {
    private final Stuff CALLS_TO = callsTo(Stuff.class); // a proxy
    public static final Command<Stuff> CMD1 = commandFor(CALLS_TO.someMethod1());
    public static final Command<Stuff> CMD2 = commandFor(CALLS_TO.someMethod2());

    // methods exist for use elsewhere, but are conveniently also wrapped as commands
    public void someMethod1() {...}
    public void someMethod2() {...}
}

class Activity {
    public void handleIt(List<Stuff> stuffs, Command<Stuff> doCmd) {
        doSomeThings();
        ...
        forEach(stuffs, doCmd);
        ...
        doOtherThings();
    }
}

共 (1) 个答案

  1. # 1 楼答案

    番石榴项目负责人凯文·布瑞利昂(Kevin Bourrillion)谈到番石榴的功能特点:

    “The syntax sucks. At the same time, this stuff is now, has always been and will always be nothing but a stopgap measure until the right language change can come along, at which time we can finally really decide on the optimal syntax and have functional-style programming start actually making lives better in Java for once. So I’m undecided how much effort to put into the Function/Predicate stuff; it’s in the library more because it sort of had to be, not so much because we think it’s a crown jewel.”

    当Java8出现时,我们可能会显著改变我们的策略,但这还不是一段时间

    此外,我们还没有发现很多用例,我们认为您描述的Command接口是最好的解决方案。例如,我们认为您上面的代码编写得更好

    for(PhoneNumber phone : phoneList) {
      phone.call();
    }
    

    老式的方式。我们可能会确信Command的优点,但我认为“for each”用例几乎总是用老式的方式做得更好