1

I am using io.vavr.control.Try and try to do Try.run but I can't use method reference with parameter. How can I fix this?

PingRequest pingRequest = new PingRequest();
PingCall pingCall = this.client.newPingCall();
//Try<Void> attempt = Try.run(pinCall::call); //A: this will work if call is a no parameter method
//Try<Void> attempt = Try.run(pinCall.call(pingRequest)); //B: I want to call it with parameter but obvious it can't: Required type: CheckedRunnable
Try<Void> attempt = Try.run(() -> pingCall.call(pingRequest)); //C: Idea pass this way, but I don't know if it's correct
attempt.onSuccess...
public PingResponse call(PingRequest input) throws InternalError {...}
Naman
  • 27,789
  • 26
  • 218
  • 353
DD Jin
  • 355
  • 1
  • 3
  • 15
  • 2
    You can't. You must rely on lambdas for this case. To simplify your question, you are asking if `Runnable r = () -> pingCall.call(pingRequest);` can be represented as `Runnable r = pingCall::call;`. See this related [Q&A](https://stackoverflow.com/questions/49830587/runnable-with-a-method-parameter) and the [other Q&A](https://stackoverflow.com/questions/38118627/how-assign-a-method-reference-value-to-runnable) as well. – Naman Mar 24 '20 at 01:46

1 Answers1

0

You can use a method reference if you first wrap a value in a Try, then mapTry the resulting value with a function provided as a method reference:

final Try<PingResponse> responseTry = Try.success(pingRequest)
    .mapTry(pingCall::call);
Nándor Előd Fekete
  • 6,988
  • 1
  • 22
  • 47