-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathResultUsage.java
More file actions
41 lines (35 loc) · 1.42 KB
/
ResultUsage.java
File metadata and controls
41 lines (35 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class ResultUsage {
public static void main(String[] args) {
// Basic usage
Result<String, Exception> success = Result.create("Successfully received data");
Result<String, Exception> failure = Result.create(new Exception("Network error"));
if (success.isSuccess()) {
System.out.println("Success: " + success.getValue());
}
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);
}
}
}