3 ms·
I'm not completely sure what this example is trying to illustrate. Most languages with proper sum types would have `Map<K, V>.get` return an `Optional<V>`. If V
by cobbal 2y ago
I'm not completely sure what this example is trying to illustrate. Most languages with proper sum types would have `Map<K, V>.get` return an `Optional<V>`. If V happens to be `Optional<Integer>`, then the result will be an `Optional<Optional<Integer>>`, which is a perfectly good type that represents the two ways a value may be missing from the map.
Am I missing something?
- pbh101 2y agoThe Map interface pre-dates Optional and does not return Optional, so it won't return an empty Optional but rather null. To be more clear: Map<K, V>.get(foo) returns a `V`, not an `Optional<V>`. If your `V` is `Optional<WrappedV>`, cool, but that doesn't change that `Map` either finds or doesn't find a V.
- stickfigure 2y agoThe parent certainly knows this. Additional methods could be added to `Map` which return `Optional`. I am annoyed by their absence every day.
- pbh101 2y agoMaybe. They didn't seem to communicate any specific knowledge of the Java standard library. Agree an Optional<V> get(K) sounds like an 'obvious' addition, though also I've found that when something 'obvious' isn't added to Java since 1.7, the explanation proffered makes sense to me.
- cogman10 2y agoJava doesn't have return type function dispatch. If you had something like: var x = map.get(k); The type of `x` could not be inferred. The best they could hope for is a signature like `Optional<V> getOpt(K);`. Which wouldn't be terribly bad as Java currently has an annoying get definition in the `Map` interface because it predates generics (The current signature is `V get(Object)`). Regardless, if they do want to change the interface, it'd probably be best if they waited for Valhalla to land. One of the problems with `Optional` as it stands is it creates a load of GC pressure. If `Optional` is converted into a value class then there will be effectively no overhead to returning it everywhere.