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.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
tsjfnoi
  • 31
  • 1
  • 3
    Please see: [the documentation of `Optional`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Optional.html), [Why should Java 8's Optional not be used in arguments](https://stackoverflow.com/questions/31922866/why-should-java-8s-optional-not-be-used-in-arguments), [Sonar RSPEC-3553](https://rules.sonarsource.com/java/RSPEC-3553) – Turing85 Feb 16 '20 at 21:53
  • 1
    @Turing85, assuming that I must (no choice in the current codebase) – tsjfnoi Feb 16 '20 at 21:55
  • 1
    Just in case you did not know, Java has its own `Optional` since Java 8. – Zabuzard Feb 16 '20 at 22:03

2 Answers2

7

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

Tix
  • 610
  • 6
  • 16
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".

Arnaud Claudel
  • 3,000
  • 19
  • 25