What is the difference between Vavr `Try.of` vs `Try.run`

8.4k Views Asked by At

Wanted more info on difference between javaslang Try.of() and Try.run()

For example

Try.of(() -> Integer.valueOf(str)).getOrElse(1) compiles fine but Try.run(() -> Integer.valueOf(str)).getOrElse(1) does not.

found in the package javaslang.control . More info on the library:

1

There are 1 best solutions below

0
On BEST ANSWER

Try.of() takes a CheckedSupplier, which has a get() method to "get a result".

Try.run() takes a CheckedRunnable, which has a void run() method to "perform side-effects".

Says so right there in the documentation.

The difference is the same as between a standard Java Supplier ("represents a supplier of results") and Runnable ("execute code ... may take any action whatsoever"). One is for retrieving a value, the other is for executing some code.

For examples of difference in use, see:

andThenTry(CheckedConsumer<? super T> consumer)

Try.of(() -> 100)
   .andThen(i -> System.out.println(i));

andThenTry(CheckedRunnable runnable)

Try.run(A::methodRef)
   .andThen(B::methodRef)
   .andThen(C::methodRef);