Default nullable implementation

This commit is contained in:
Andrea Cavalli 2022-05-06 10:07:33 +02:00
parent c3564e049b
commit 3878fac9f5
2 changed files with 49 additions and 3 deletions

View File

@ -7,12 +7,14 @@ public interface NativeNullable<T> {
boolean isEmpty();
boolean isPresent();
default boolean isPresent() {
return !isEmpty();
}
@NotNull
T orElse(@NotNull T defaultValue);
@NotNull NativeNullable<T> or(@NotNull NativeNullable<? extends T> fallback);
@NotNull NativeNullable<? extends T> or(@NotNull NativeNullable<? extends T> fallback);
@Nullable
T getNullable();

View File

@ -1,9 +1,53 @@
package it.cavallium.data.generator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface TypedNullable<T> extends NativeNullable<T> {
@NotNull
T get() throws NullPointerException;
default T get() throws NullPointerException {
var value = getNullable();
if (value == null) {
throw new NullPointerException();
} else {
return value;
}
}
@Override
default @Nullable T getNullable(@Nullable T defaultValue) {
var value = getNullable();
return value == null ? defaultValue : value;
}
@Override
default @NotNull T orElse(@NotNull T defaultValue) {
var value = getNullable();
if (value == null) {
throw new NullPointerException();
} else {
return value;
}
}
@Override
default @NotNull NativeNullable<? extends T> or(@NotNull NativeNullable<? extends T> fallback) {
var value = getNullable();
if (value == null) {
return fallback;
} else {
return this;
}
}
@Override
default boolean isPresent() {
return getNullable() != null;
}
@Override
default boolean isEmpty() {
return getNullable() == null;
}
}