2

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:

DavidS
  • 5,022
  • 2
  • 28
  • 55
ag157
  • 85
  • 1
  • 7
  • Where did you get these `Try` methods? They are not built into Java. – Basil Bourque Jul 14 '20 at 16:35
  • found it in the package `javaslang.control` . https://www.javadoc.io/doc/io.javaslang/javaslang/2.0.6/javaslang/control/Try.html – ag157 Jul 14 '20 at 16:37
  • 2
    Provide that detail as an edit your Question rather than as a Comment – Basil Bourque Jul 14 '20 at 16:38
  • `of` accepts a `Supplier`, allowing you to specify a value which can be obtained via `get` after execution finished. `run` does *not* allow you to supply a value obtainable via `get`. If you're familiar with `ExecutorService`, it's similar to `submit(Runnable)` vs `sumbit(Callable)` – Vince Jul 14 '20 at 16:46
  • 1
    I think you're getting some confusion here because the library's old name, "javaslang", sounds so much like a standard library, "java.lang", that your question looks like a total mistake. I've edited your title and added a link to the project's homepage. – DavidS Jul 14 '20 at 17:19

1 Answers1

3

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);
Andreas
  • 154,647
  • 11
  • 152
  • 247