I didn't know how to use Optional, but I understood that it was something like this.
hoge
only when the variable hoge
is not null
python
if (hoge != null) {
hoge.fuga();
}
python
Optional
.ofNullable(hoge)
.ifPresent(o -> o.fuga());
Which one is easier to see? : smile:
hoge
is not null
, the method execution result of hoge
is returned.python
fugo = hoge != null ? hoge.fugo() : null;
python
fugo = Optional
.ofNullable(hoge)
.map(o -> o.fugo()) // Optional<?>Will be returned, so
.orElse(null); //Make orElse return the value itself or the default value (null here)
Is it easier to see the ternary operator at this level? : smile:
hoge
is not null
, call the method of hoge
, and if the result of the method is not null
, call the method further.I don't know what it says. Look at the code.
python
instant = null;
if (hoge != null) {
date = hoge.getDate();
if (date != null) {
instant = date.toInstant();
}
}
Or how about this?
python
instant = hoge != null
? (hoge.getDate() != null
? hoge.getDate().toInstant()
: null)
: null;
instant = Optional
.ofNullable(hoge)
.map(o -> o.getDate())
.map(d -> d.toInstant())
.orElse(null);
Which one is easier to see? : smile:
Recommended Posts