Reputation: 251
I have created a solution for optionals in Java.
public final class Optional<T> {
private final T reference;
private Optional(T reference) {
this.reference = reference;
}
public T get() {
if (!isPresent()) {
throw new IllegalStateException("Cannot retrieve reference when absent!");
}
return reference;
}
public boolean isPresent() {
return reference != null;
}
public static <T> Optional<T> of(T reference) {
return new Optional<T>(reference);
}
public static <T> Optional<T> absent() {
return of(null);
}
public static <T> Optional<T> fromNullable(@Nullable T nullableReference) {
return of(nullableReference);
}
}
But when I am using it in my production code, the compiler complains.
This is my production code:
public final class OnsetSequencer {
private final Onset onset;
private final Optional<EventManager> eventManager;
public OnsetSequencer(Onset onset, Optional<EventManager> eventManager) {
this.onset = onset;
this.eventManager = eventManager;
}
public OnsetSequencer(Onset onset) {
this(onset, Optional.absent());
}
public void sequence() {
boolean present = eventManager.isPresent();
if (present) {
eventManager.get().dispatchEvent(new OnsetBeginEvent(onset));
}
onset.begin();
if (present) {
eventManager.get().dispatchEvent(new OnsetEndEvent(onset));
}
onset.end();
}
}
The compiler complains at this(onset, Optional.absent());
saying: The constructor OnsetSequencer(Onset, Optional) is undefined
I have tried to fix the issue by changing it to this(onset, Optional<EventManager>.absent());
That syntax is wrong as well.
I am wondering how to fix this issue!
Upvotes: 0
Views: 98
Reputation: 1500225
I think you want:
Optional.<EventManager>absent()
I've never liked the way of expressing type arguments for generic methods in Java, but such is life. See section 15.12 of the JLS for details.
Upvotes: 3