Skip to content

Commit 20c362e

Browse files
Merge pull request #141 from SimonHarmonicMinor/feature/#140-try-monad-lazy
Feature/#140 try monad lazy
2 parents 8a5b5af + e9e4604 commit 20c362e

File tree

3 files changed

+278
-541
lines changed

3 files changed

+278
-541
lines changed

README.md

+26-2
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ This library has two monads: [`Try`](#try) and [`Lazy`](#lazy).
102102
###### Try
103103

104104
`Try` allows you to work with methods that may throw an exception
105-
in the same way as `Optional`. For instance, suppose we have such code:
105+
in the same way as `Optional` in a **lazy** way. For instance, suppose we have such code:
106106

107107
```java
108108
int num;
@@ -127,7 +127,7 @@ JUU allows to rewrite this snippet as two equations:
127127

128128
```java
129129
int num = Try.of(() -> Integer.parseInt(getStringValue()))
130-
.orElse(getDefaultIntValue());
130+
.orElseGet(() -> getDefaultIntValue());
131131
return Try.of(() -> executeRpc(num))
132132
.orElse(SOME_DEFAULT_VALUE);
133133
```
@@ -190,6 +190,30 @@ The class only catches `Exception` type.
190190
It means that all `Throwable` instances are skipped.
191191
The motivation is that `Error` extends from `Throwable` but these exceptions should not be caught manually.
192192

193+
The fact that `Try` monad acts *lazily* means
194+
that you build a pipeline of execution that triggers on any *terminal* operation.
195+
196+
```java
197+
Try<Integer> t = Try.of(() -> {
198+
println("First step");
199+
return 1;
200+
}).map(val -> {
201+
println("Second step");
202+
return val + 1;
203+
}).filter(val -> {
204+
println("Third step");
205+
return val > 0;
206+
});
207+
// nothing prints here
208+
209+
assert 2 == t.orElseThrow();
210+
// First step
211+
// Second step
212+
// Third step
213+
```
214+
215+
All terminal operations are listed in the [javadoc](./src/main/java/com/kirekov/juu/monad/Try.java).
216+
193217
###### Lazy
194218

195219
The name of the monad defines its purpose.

0 commit comments

Comments
 (0)