Instead of initialising optCar
variable as below:
Optional<'Car'> optCar = Optional.of(car);
Why not initialise it simply as :
Car optCar = car;
When a business logic does not permit car to be null?
Instead of initialising optCar
variable as below:
Optional<'Car'> optCar = Optional.of(car);
Why not initialise it simply as :
Car optCar = car;
When a business logic does not permit car to be null?
You totally can.
Optional is for situations where you would have a code
If(object == null) {…
Instead you use Optional and then you have cool access to stream like features and or/or else statements that make ur code so much nicer, for example:
return Optional.ofNullable(object).orElse(defaultObject);
Or another example
return Optional.ofNullable(object).map(Object::toString).orElseThrow();
This last code return string representation of ur object if that optional is present or else throws an exception. orElseThrow is most useful in situations where you actually are sure that object is always there so such situation will likely never arise and if it does u know where to look.
But like I said in the beginning if you don’t need these features u don’t need to use it
if you are sure that car
can never be null then using Optional would be an overkill.
The presence of Optional is to provide for clarity that this particular instance can be null and the Optional needs to be unwrapped and explicitly checked for the absence (or presence) of a value.
Do not go by what I say, hear it from the expert:
Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.
Excerpted from Brian Goetz's answer here.