3 ms·
> Is there any static check to make sure this can't happen, or is it something you have to just avoid? I can imagine someone might accidentally return `null` in
by richbell 5y ago
> Is there any static check to make sure this can't happen, or is it something you have to just avoid? I can imagine someone might accidentally return `null` instead of `Optional.ofNullable(null)
The latter. Java's Optionals are half-baked and don't provide as much safety as you'd think because it's easy for a `null` value to slip in. Notice how they used `Optional.ofNullable` — a common footgun is using `Optional.of(value)`, which throws a NullPointerException if `value` is null[1].
[1] https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#of-T- https://docs.oracle.com/javase/8/docs/api/java/util/Optional...
- d3nj4l 5y agoThis is true, but I think half-baked safety is way better than no safety, and in practice I've found that it's actually pretty difficult for a null to slip in, because that only realistically happens when you're directly assigning values. Library code that returns optionals has never caused any issues IME, and custom code that returns optionals is super easy to review because there's only one good way to make an optional - ofNullable.