What is Optional in Java, and what is it actually for?
Optional is a small container that may hold a value and may hold nothing at all. It is there for one job, which is to say clearly in the type that a result might not be there.
import java.util.List;
import java.util.Optional;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace");
// The lookup may or may not find something.
Optional<String> found = find(names, "Grace");
Optional<String> missing = find(names, "Alan");
System.out.println("found : " + found.orElse("nobody"));
System.out.println("missing : " + missing.orElse("nobody"));
// The point is that the caller has to deal with the case.
System.out.println("is present : " + found.isPresent());
}
static Optional<String> find(List<String> names, String wanted) {
for (String name : names) {
if (name.equals(wanted)) {
return Optional.of(name);
}
}
return Optional.empty();
}
}
The value of it is that the possibility is written into the signature. A method that returns a String could give you null and you would not know. A method that returns an Optional<String> says that there might be nothing, and the compiler makes the caller deal with it.
It is meant for the case where "no result" is a normal answer rather than a failure. A lookup that finds nothing, a setting that is not set, a value that has been deleted. It is not meant for the case where the failure is an error, because then an exception is the better answer.
The next question in this topic looks at the mistakes that people make with it.