Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you create a <code>Future</code> (using <code>scala.concurrent.future</code>) it <strong>will</strong> be calculated, no matter what you do. So you need a totally different strategy.</p> <p>Further, your interface does not even remotely allow to figure out what data you will actually use. How should the calculation of <code>myCalc</code> know that in the <code>onComplete</code> you'll only use <code>result1</code>?</p> <p>You could:</p> <ul> <li><p>Use only lazy vals:</p> <pre><code>val calculator = new Calculator { lazy val hardToCalculate1 = { println("calculating 1") 1 } // ... } </code></pre> <p>Pro: Simple<br /> Con: Not asynchronous</p></li> <li><p>Encapsulate the <code>Future</code> to allow requesting the calculation:</p> <pre><code>class ReqFuture[T](body: () =&gt; T) { lazy val fut = future { body() } } </code></pre> <p>But now you still have the problem that <code>myCalc</code> will request and wait for all of them. So you'll have to introduce <code>ReqFutures</code> in <code>Calculator</code>:</p> <pre><code>trait Calculator { def hardToCalculate1: ReqFuture[Int] // ... def result1 = for { h1 &lt;- hardToCalculate1.fut h2 &lt;- hardToCalculate2.fut } yield h1 + h2 } </code></pre> <p>Pro: When you call <code>result1</code>, only what you need is calculated (but still only once).<br/> Con: <code>result1</code> is a <code>Future[Int]</code> now. So <code>Futures</code> have fully penetrated your <code>Calculator</code>.</p></li> </ul> <p>If you cannot influence <code>Calculator</code> (what I am suspecting) and cannot change the code of <code>result1,2,3</code> there is unfortunately nothing in my knowledge that you can do to make execution lazy and asynchronous.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload