Skip to content

ashr123/option

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

50 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Maven Central

Option

Small package that brings DOP of Optional to Java.

Gives you the possibility to write code as

import io.github.ashr123.option.None;
import io.github.ashr123.option.Option;
import io.github.ashr123.option.Some;

public record Pair<L, R>(L left, R right) {
}

public static Integer intABSOption(Integer integer) {
	return switch (Option.of(integer)) {
		case Some(Integer i) when i < 0 -> -i;
		case Some(Integer i) -> i;
		case None<Integer> ignored -> null;
		case None() -> null; // effectively same as the case above
	};
}

public static Integer intMax(Pair<Integer, Integer> pair) {
	return switch (Option.of(pair)) {
		case Some(Pair(Integer l, Integer r)) when l != null && r == null -> l;
		case Some(Pair(Integer l, Integer r)) when l == null && r != null -> r;
		case Some(Pair(Integer l, Integer r)) when l != null && r != null && l > r -> l;
		case Some(Pair(Integer l, Integer r)) -> r;
		case None() -> null;
	};
}

Comparison against existing Optional<T>

Optional methods Option<T> opt equivalent
empty() new None<>()
of(T value) new Some<>(T value)
ofNullable(T value)
  • of(T value)
  • of(Optional<T> value)
get()
  • switch-case
  • if (opt instanceof Some(T value)) ...
isPresent() if (opt instanceof Some<?>) ...
isEmpty() if (opt instanceof None<?>) ...
ifPresent(Consumer<? super T> action)
  • switch-case
  • if (opt instanceof Some(T value)) value ...
ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) switch-case
filter(Predicate<? super T> predicate) if (opt instanceof Some(T value) && value ...)
map(Function<? super T, ? extends U> mapper) if (opt instanceof Some(T value)) value ...
flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) flatMap(Function<? super T, ? extends Option<? extends U>> mapper)
or(Supplier<? extends Optional<? extends T>> supplier) switch-case
stream() stream()
orElse(T other) switch-case
orElseGet(Supplier<? extends T> supplier) switch-case
orElseThrow() switch-case
orElseThrow(Supplier<? extends X> exceptionSupplier) switch-case

Requires JRE 21 or above.