我正在经历
Vavr Usage Guide
的一节介绍了如何使用Match和他们所称的其他“语法糖”来执行副作用。这里给出了一个示例:
Match(arg).of(
Case($(isIn("-h", "--help")), o -> run(this::displayHelp)),
Case($(isIn("-v", "--version")), o -> run(this::displayVersion)),
Case($(), o -> run(() -> {
throw new IllegalArgumentException(arg);
}))
);
然后讨论如何
run
不得在lambda车身等外部运行。
IMHO,解释中缺少一些东西来让我完全清楚,即
跑
某个Vavr接口上的现有方法(我找不到),还是应该是我自己在周围代码库中的方法?
因此,我尝试并详细说明了上面的示例,只是为了让我能够运行并看到结果:
@Test public void match(){
String arg = "-h";
Object r = Match(arg).of(
Case($(isIn("-h", "--help")), o -> run(this::displayHelp)),
Case($(isIn("-v", "--version")), o -> run(this::displayVersion)),
Case($(), o -> run(() -> {
throw new IllegalArgumentException(arg);
}))
);
System.out.println(r);
}
private Void run(Supplier<String> supp) {
System.out.println(supp.get());
return null;}
private String displayHelp() {return "This is a help message.";}
private String displayVersion() {return "This is a version message.";}
有没有人能确认一下,我在Vavr的设计师们所设想的功能方面是否走对了轨道,或者我是否完全偏离了正轨,在这种情况下,我希望能得到一些指导。
提前谢谢你。
更新日期:
import static io.vavr.API.run;
@Test public void match1() {
String arg = "-h";
Object r = Match(arg).of(
Case($(isIn("-h", "--help")), o -> run(this::displayHelp)),
Case($(isIn("-v", "--version")), o -> run(this::displayVersion)),
Case($(), o -> run(() -> {
throw new IllegalArgumentException(arg);
}))
);
System.out.println("match: " +r);
}
//private Void run(Supplier<Void> supp) {supp.get();}
private void displayHelp() {System.out.println("This is a help message.");}
private void displayVersion() {System.out.println("This is a version message.");}