我有下面的代码,对于多次空检查有点难看.
String s = null;
if (str1 != null) {
s = str1;
} else if (str2 != null) {
s = str2;
} else if (str3 != null) {
s = str3;
} else {
s = str4;
}
Run Code Online (Sandbox Code Playgroud)
所以我尝试使用Optional.ofNullable如下所示,但如果有人读取我的代码仍然很难理解.在Java 8中这样做的最佳方法是什么.
String s = Optional.ofNullable(str1)
.orElse(Optional.ofNullable(str2)
.orElse(Optional.ofNullable(str3)
.orElse(str4)));
Run Code Online (Sandbox Code Playgroud)
在Java中9,我们可以使用Optional.ofNullable同OR,但在Java8还有没有其他办法?
在Swift中给出以下内容:
var optionalString: String?
let dict = NSDictionary()
Run Code Online (Sandbox Code Playgroud)
以下两个陈述之间的实际区别是什么:
optionalString = dict.objectForKey("SomeKey") as? String
Run Code Online (Sandbox Code Playgroud)
VS
optionalString = dict.objectForKey("SomeKey") as! String?
Run Code Online (Sandbox Code Playgroud) 当我设置firstThing为默认值时,nil这将起作用,没有默认值nil我得到一个错误,即调用函数时有一个缺少的参数.
通过键入Int?我认为它使其成为可选的默认值nil,我是对的吗?如果是这样的话,为什么没有它= nil呢?
func test(firstThing: Int? = nil) {
if firstThing != nil {
print(firstThing!)
}
print("done")
}
test()
Run Code Online (Sandbox Code Playgroud) 在Swift中,如何在switch语句中编写一个case来测试根据可选内容切换的值,如果可选包含,则跳过case nil?
以下是我的想象:
let someValue = 5
let someOptional: Int? = nil
switch someValue {
case someOptional:
// someOptional is non-nil, and someValue equals the unwrapped contents of someOptional
default:
// either, someOptional is nil, or someOptional is non-nil but someValue does not equal the unwrapped contents of someOptional
}
Run Code Online (Sandbox Code Playgroud)
如果我只是这样编写它,编译器抱怨someOptional没有解开,但如果我通过添加!到结尾显式解包,我当然会在任何时候someOptional包含运行时错误nil.添加?而不是!对我有意义(在可选链接的精神,我想),但不会使编译器错误消失(即实际上不打开可选的).
我试图理解Java 8中API 的ifPresent()方法Optional.
我有简单的逻辑:
Optional<User> user=...
user.ifPresent(doSomethingWithUser(user.get()));
Run Code Online (Sandbox Code Playgroud)
但这会导致编译错误:
ifPresent(java.util.functionError:(186, 74) java: 'void' type not allowed here)
Run Code Online (Sandbox Code Playgroud)
我当然可以这样做:
if(user.isPresent())
{
doSomethingWithUser(user.get());
}
Run Code Online (Sandbox Code Playgroud)
但这就像一张杂乱无章的null支票.
如果我将代码更改为:
user.ifPresent(new Consumer<User>() {
@Override public void accept(User user) {
doSomethingWithUser(user.get());
}
});
Run Code Online (Sandbox Code Playgroud)
代码变得越来越脏,这让我想到回到旧的null支票.
有任何想法吗?
为什么这会抛出java.lang.NullPointerException?
List<String> strings = new ArrayList<>();
strings.add(null);
strings.add("test");
String firstString = strings.stream()
.findFirst() // Exception thrown here
.orElse("StringWhenListIsEmpty");
//.orElse(null); // Changing the `orElse()` to avoid ambiguity
Run Code Online (Sandbox Code Playgroud)
第一项strings是null,这是一个完全可以接受的值.此外,findFirst()返回一个Optional,这对于findFirst()能够处理nulls 更有意义.
编辑:更新orElse()不那么模棱两可.
当我想检查一个Optional Bool是否为true时,执行此操作不起作用:
var boolean : Bool? = false
if boolean{
}
Run Code Online (Sandbox Code Playgroud)
它导致此错误:
可选类型'@IvalueBool?' 不能用作布尔值; 测试'!= nil'而不是
我不想检查零; 我想检查返回的值是否为true.
if boolean == true如果我正在使用Optional Bool,我是否总是必须这样做?
由于Optionals不再符合BooleanType,编译器是否应该知道我想检查Bool的值?
从beta 8.3开始,zillions警告"字符串插值会为可选值生成调试描述;你的意思是明确说明吗?" 出现在我的代码中.
例如,警告在以下情况下弹出,其中选项可能导致nil:
let msg = "*** Error \(options["taskDescription"]): cannot load \(sUrl) \(error)"
Run Code Online (Sandbox Code Playgroud)
如前所述,我(和编译器)可以将选项插值为'nil'.但是编译器改变了主意.
编译器建议添加一个带有描述的String构造函数,如下所示:
let msg = "*** Error \(String(describing: options["taskDescription"])): cannot load \(sUrl) \(error)"
Run Code Online (Sandbox Code Playgroud)
显然,结果是明确的,但在我看来也非常麻烦.有更好的选择吗?我是否必须修复所有警告或更好等待下一个测试版?
为了帮助理解monad是什么,有人可以使用java提供一个例子吗?他们有可能吗?
如果你从这里下载预发布的lambda兼容JDK8,可以使用java表达lambda表达式http://jdk8.java.net/lambda/
使用此JDK的lambda示例如下所示,有人可以提供相对简单的monad吗?
public interface TransformService {
int[] transform(List<Integer> inputs);
}
public static void main(String ars[]) {
TransformService transformService = (inputs) -> {
int[] ints = new int[inputs.size()];
int i = 0;
for (Integer element : inputs) {
ints[i] = element;
}
return ints;
};
List<Integer> inputs = new ArrayList<Integer>(5) {{
add(10);
add(10);
}};
int[] results = transformService.transform(inputs);
}
Run Code Online (Sandbox Code Playgroud) 我正在使用Boost程序选项库来解析命令行参数.
我有以下要求:
我怎么处理这个?这是我的代码处理这个,我发现它非常多余,我认为必须有一个容易做的,对吧?
#include <boost/program_options.hpp>
#include <iostream>
#include <sstream>
namespace po = boost::program_options;
bool process_command_line(int argc, char** argv,
std::string& host,
std::string& port,
std::string& configDir)
{
int iport;
try
{
po::options_description desc("Program Usage", 1024, 512);
desc.add_options()
("help", "produce help message")
("host,h", po::value<std::string>(&host), "set the host server")
("port,p", po::value<int>(&iport), "set the server port")
("config,c", po::value<std::string>(&configDir), "set the config path")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return false;
}
// There …Run Code Online (Sandbox Code Playgroud)