3

Is there a "nice" way to create a copy of an Optional object?

For example, say I have a method

Optional<Obj> doSomeStuff(Optional<Obj> input){
   if(something){
     return Optional.copyOf(input); // does this exist in some Guava library or something?
   }
   // ...
}

Basically, I want to have immutability so that I don't pass the same Optional around, and if something gets triggered then I want to make sure that I create a brand new Optional with same contents of the input Optional (whether it be empty or not).

Is there any clean way to do it? The Optional.copyOf method does not exist.

3

2 Answers 2

7

The Optional class is immutable, so you do not need copy,. You can just do return input.

3

Guava Optional is already immutable. You don't need to make a copy of it.

Here is the beginning of the javadoc:

An immutable object that may contain a non-null reference to another object. Each instance of this type either contains a non-null reference, or contains nothing (in which case we say that the reference is "absent"); it is never said to "contain null".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.