From ec9418c623ff9539654d4151bd30c668f3258c43 Mon Sep 17 00:00:00 2001 From: Laifsyn <99366187+Laifsyn@users.noreply.github.com> Date: Wed, 10 Apr 2024 13:33:44 -0500 Subject: [PATCH] Basic Result implementation --- src/main/java/com/utp/utils/Result.java | 52 +++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/main/java/com/utp/utils/Result.java diff --git a/src/main/java/com/utp/utils/Result.java b/src/main/java/com/utp/utils/Result.java new file mode 100644 index 0000000..ba6643f --- /dev/null +++ b/src/main/java/com/utp/utils/Result.java @@ -0,0 +1,52 @@ +package com.utp.utils; + +import java.util.Optional; +import java.util.function.Function; + +public class Result { + + private Optional value; + private Optional error; + + private Result(T value, E error) { + this.value = Optional.ofNullable(value); + this.error = Optional.ofNullable(error); + } + + public static Result ok(U value) { + return new Result<>(value, null); + } + + public static Result error(E error) { + return new Result<>(null, error); + } + + public boolean isError() { + return error.isPresent(); + } + + public boolean isOk() { + return value.isPresent(); + } + + public T unwrapOk() throws RuntimeException { + if (this.isError()) + throw new RuntimeException("Called unwrapOk on an error Result"); + return value.get(); + } + + public E unwrapError() throws RuntimeException { + if (this.isOk()) + throw new RuntimeException("Called unwrapError on an ok Result"); + return error.get(); + } + + public Result flatMap(Function> mapper) { + + if (this.isError()) { + return Result.error(error.get()); + } + + return mapper.apply(value.get()); + } +}