You can do it like this:
(您可以这样做:)
Integer total = Optional.of(new Integer(10)).orElse(null);
And if the Optional
value can be nullable then:
(如果Optional
值可以为空,则:)
Integer total = Optional.ofNullable(new Integer(10)).orElse(null);
Optional.ofNullable
will prevent NPE in case of null
value.
(Optional.ofNullable
将在出现null
值时阻止NPE 。)
The reason you're getting this error in the first example is that in lambda expression you're not allowed to change the reference of the local variables.
(在第一个示例中出现此错误的原因是,在lambda表达式中,您不允许更改局部变量的引用。)
That's why they need to be either declared final
or effectively final. (这就是为什么需要将它们声明为final
或有效地为final的原因。)
And the reason the second example is working because here you're not changing the reference of the total
variable.
(第二个示例之所以起作用的原因是,这里您没有更改total
变量的引用。)
You're only updating its value using its set()
method. (您仅使用其set()
方法更新其值。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…