5 ms·
The author noted it, but still, all listed Optional/Maybe “disadvantages” apply to Java specifically and don't really apply to the languages where it was availa
by danabramov 12y ago
The author noted it, but still, all listed Optional/Maybe “disadvantages” apply to Java specifically and don't really apply to the languages where it was available from the beginning and has some kind of syntax support.
- nixpulvis 12y agoCough... Rust... Cough.
- dllthomas 12y agoIt doesn't even need syntax support, if you are comfortable with higher order functions. Java's approach of forcing the same "check, use" pattern on you makes their Optional only a modest gain. Compare with Haskell's maybe function: maybe :: b -> (a -> b) -> Maybe a -> b You provide a default result, a function from the value (if it's there) to that result type, and the optional value. There is no way to use this wrong - you can't forget to check because there is no check. Edited to add: Apparently Java does hand you the tools to do it right, if a little ugly, using ifPresent and a purpose-built Consumer. My Java is rusty, but I'll try and put an example together in a bit.
- dllthomas 12y agoSo, you can do the following: interface OverOptional<S,T> extends Consumer<T> { public S getResult(); }; Which allows you to create an anonymous class that embodies the first two arguments of maybe: Optional<Integer> maybe_int = Optional.of(7); OverOptional<Boolean, Integer> is_seven_or_empty = new OverOptional<Boolean, Integer>() { private Boolean result = true; // default public void accept(Integer i) { result = i == 7; } public Boolean getResult() { return result; } }; maybe_int.ifPresent(is_seven_or_empty); return is_seven_or_empty.getResult();