Though it is similar to languages like C#, Java has some unique features that help improve programs. One feature, the Optional
class, indicates whether a value exists or not—it is a way to clarify logic in modern Java programs. I think it is a great feature.
Here's why—without Optional
, we might use magic constants on a value like an Int to indicate that no value exists. But with Optional
, we can just use Optional.empty
and our logic is clearer. Optional
in Java is similar to Option
in Rust, and an equivalent feature in Swift.
When considering Optional
, we should remember that:
isPresent
, isEmpty
, and use other methods with lambda expressions.By storing an Optional
int in a class, we indicate that the value may or may not exist. So every time we access the field, we must use methods on the Optional
to get its inner value. Still, Optional
is useful in clarifying when a field is valid—and it is one of my favorite Java features.