Ken*_*Ken 2 java optional java-8
我有一个Optional并且想要调用一个带有'内容的函数(如果存在),如果没有则抛出.问题是map不会采用无效方法.
File file;
//...
Optional maybeFile = Optional.ofNullable(file);
//..
maybeFile
.map(f -> writeTo(f, "stuff")) //Compile error: writeTo() is void
.orElseThrow(() -> new IllegalStateException("File not set"));
Run Code Online (Sandbox Code Playgroud)
如何在保持writeTo无效的同时实现这一点?
orElseThrow 返回File对象(如果存在),因此您可以将其写为
writeTo(maybeFile.orElseThrow(() -> new IllegalStateException("File not set")), "stuff");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |