Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a Guava Optional

Tags:

java

guava

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.

like image 233
tsjfnoi Avatar asked Mar 17 '26 08:03

tsjfnoi


1 Answers

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

like image 154
Tix Avatar answered Mar 19 '26 20:03

Tix