Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Add one more usage example of Result
  • Loading branch information
mari4kaa committed Jun 18, 2025
commit 9254e0e2c6d8887c0fed401089cc1410399165dc
4 changes: 2 additions & 2 deletions Java/Result/Result.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static <T> Result<T, Exception> fromValue(T value) {
return new Result<>(value, null);
}

public static <E extends Exception> Result<Void, E> fromError(E error) {
public static <T, E extends Exception> Result<T, E> fromError(E error) {
return new Result<>(null, error);
}

Expand All @@ -36,4 +36,4 @@ public T getValue() {
public E getError() {
return error;
}
}
}
30 changes: 28 additions & 2 deletions Java/Result/ResultUsage.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
public class ResultUsage {
public static void main(String[] args) {
// Usage
// Basic usage
Result<String, Exception> success = Result.create("Successfully received data");
Result<String, Exception> failure = Result.create(new Exception("Network error"));

Expand All @@ -11,5 +11,31 @@ public static void main(String[] args) {
if (failure.isError()) {
System.out.println("Failure: " + failure.getError().getMessage());
}

// Additional usage example
// Handling a method that may throw and wrapping the result
Result<Integer, Exception> result1 = parseIntSafe("123");
Result<Integer, Exception> result2 = parseIntSafe("abc");

if (result1.isSuccess()) {
System.out.println("Parsed value: " + result1.getValue());
} else {
System.out.println("Parse error: " + result1.getError().getMessage());
}

if (result2.isSuccess()) {
System.out.println("Parsed value: " + result2.getValue());
} else {
System.out.println("Parse error: " + result2.getError().getMessage());
}
}

public static Result<Integer, Exception> parseIntSafe(String input) {
try {
int value = Integer.parseInt(input);
return Result.fromValue(value);
} catch (Exception e) {
return Result.fromError(e);
}
}
}
}