|
|
|
|
|
by waps
4541 days ago
|
|
Problems : 1) How do you get at the value itself ? (Casting ? That's bad) 2) How do you prevent in Maybe<Integer> x; x == null ? 3) How do you prevent someone from extending Maybe<T> ? e.g. public final class LetsHaveFun<T> implements Maybe<T> {
public boolean hasValue() { throw Exception("Can't touch this");
}
4) (you need a null check in the constructor)5) (I dislike the autoboxing this uses) |
|
You could add the usual map method to the Maybe type - a Maybe<T> can take a Function<T, U>, and returns a Maybe<U>. If it's None, it doesn't call the function, and just returns None; if it's Some, it calls it with the value, and wraps the result in a new Some. If you want to do side-effects conditionally on whether the value is there, you just do them in the Function and return some placeholder value. You could write a trivial adaptor to take an Effect<T> and convert to to a Function<T, Void>, etc.
> 2) How do you prevent in Maybe<Integer> x; x == null ?
You're right that using a Maybe does not exclude the ability to use nulls. Nobody can deny that. The point i was making is that there is nothing useful that you can do with nulls that you cannot do with a Maybe instead.
> 3) How do you prevent someone from extending Maybe<T> ? e.g.
You can trivially control extension by making Maybe an abstract class, giving it a private constructor, and making Some and None static inner classes of it. It's a kludge, but it works!