This repository has been archived by the owner on Aug 9, 2024. It is now read-only.
generated from microsoft/vscode-remote-try-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package com.utp.utils; | ||
|
||
import java.util.Optional; | ||
import java.util.function.Function; | ||
|
||
public class Result<T, E> { | ||
|
||
private Optional<T> value; | ||
private Optional<E> error; | ||
|
||
private Result(T value, E error) { | ||
this.value = Optional.ofNullable(value); | ||
this.error = Optional.ofNullable(error); | ||
} | ||
|
||
public static <U, E> Result<U, E> ok(U value) { | ||
return new Result<>(value, null); | ||
} | ||
|
||
public static <U, E> Result<U, E> 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 <U> Result<U, E> flatMap(Function<T, Result<U,E>> mapper) { | ||
|
||
if (this.isError()) { | ||
return Result.error(error.get()); | ||
} | ||
|
||
return mapper.apply(value.get()); | ||
} | ||
} |