|
|
|
|
|
by anon4
4540 days ago
|
|
Oh come on, that's trivial public interface Maybe<T> {
boolean hasValue();
}
public final class Just<T> implements Maybe<T> {
public final T value;
public Just(T value) {
this.value = value;
}
public boolean hasValue() { return true; }
}
public final class Nothing<T> implements Maybe<T> {
public boolean hasValue() { return false; }
}
You can even get rid of hasValue (but then you need to pay for instanceof each time); or of the Nothing class and make Maybe a class. You may ask what the value of Just.value is before the constructor runs - the value is a machine null and if you somehow manage to access it before the ctor runs, that's a NullPointerException; or what writing "Type varname;" in a function would do - that would be perfectly legal, but you won't be allowed to use it if the compiler can't prove you've initialised it first (which it does right now). |
|
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.
4) (you need a null check in the constructor)5) (I dislike the autoboxing this uses)