`Objects.isNull`与`Optional.ofNullable`

huangapple go评论60阅读模式
英文:

Objects.isNull vs. Optional.ofNullable

问题

以下是翻译好的内容:

我有这段用于测试的代码片段

if (Objects.isNull(o)) {
    return null;
}
return String.valueOf(o);

当我用这段代码替换时

Optional.ofNullable(String.valueOf(o)).orElse(null);

在我的测试中,我得到了这个断言错误:

期望: "<null>"
要等于: <null>
但实际并非如此。
英文:

I have this piece of code used in a test

if (Objects.isNull(o)) {
			return null;
		}
		return String.valueOf(o);	

and when I replace this piece of code with

Optional.ofNullable(String.valueOf(o)).orElse(null);

I have this assertion error in my tests:

Expecting: &lt;&quot;null&quot;&gt;
to be equal to: &lt;null&gt;
but was not.

答案1

得分: 2

`Optional.ofNullable(String.valueOf(o))` 当 `o == null` 时不会是一个空的 Optional,因为 `String.valueOf(null)` 会返回字符串 `"null"`。

正确的 Optional 使用方式是:

    Optional.ofNullable(o).map(String::valueOf).orElse(null);

在这种方式中,`ofNullable(null)` 会生成一个空的 Optional,导致最终会调用 `orElse(null)`。
英文:

Optional.ofNullable(String.valueOf(o)) will not be an empty optional when o == null, because String.valueOf(null) returns the String &quot;null&quot;.

The correct use of optional there is:

Optional.ofNullable(o).map(String::valueOf).orElse(null);

Where ofNullable(null) will make an empty optional, causing orElse(null) to be eventually invoked.

答案2

得分: 1

String.valueOf() 如果对象不为null,则返回对象的toString(),否则返回字符串"null"。

直接来自String类:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

这意味着在你的断言中,你正在测试"null"是否等于null,这会导致失败。

英文:

String.valueOf() return toStirng() of an object if not null or return "null" string

straight from the String class:

public static String valueOf(Object obj) {
        return (obj == null) ? &quot;null&quot; : obj.toString();
    }

that means in your assertion you are testing "null" equals null which get fail.

huangapple
  • 本文由 发表于 2020年10月21日 18:09:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/64461285.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定