Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's <a href="https://stackoverflow.com/users/65133/james-iry">James Iry</a> solution using continuations:</p> <pre><code>// standard using block definition def using[X &lt;: {def close()}, A](resource : X)(f : X =&gt; A) = { try { f(resource) } finally { resource.close() } } // A DC version of 'using' def resource[X &lt;: {def close()}, B](res : X) = shift(using[X, B](res)) // some sugar for reset def withResources[A, C](x : =&gt; A @cps[A, C]) = reset{x} </code></pre> <p>Here are the solutions with and without continuations for comparison:</p> <pre><code>def copyFileCPS = using(new BufferedReader(new FileReader("test.txt"))) { reader =&gt; { using(new BufferedWriter(new FileWriter("test_copy.txt"))) { writer =&gt; { var line = reader.readLine var count = 0 while (line != null) { count += 1 writer.write(line) writer.newLine line = reader.readLine } count } } } } def copyFileDC = withResources { val reader = resource[BufferedReader,Int](new BufferedReader(new FileReader("test.txt"))) val writer = resource[BufferedWriter,Int](new BufferedWriter(new FileWriter("test_copy.txt"))) var line = reader.readLine var count = 0 while(line != null) { count += 1 writer write line writer.newLine line = reader.readLine } count } </code></pre> <p>And here's Tiark Rompf's suggestion of improvement:</p> <pre><code>trait ContextType[B] def forceContextType[B]: ContextType[B] = null // A DC version of 'using' def resource[X &lt;: {def close()}, B: ContextType](res : X): X @cps[B,B] = shift(using[X, B](res)) // some sugar for reset def withResources[A](x : =&gt; A @cps[A, A]) = reset{x} // and now use our new lib def copyFileDC = withResources { implicit val _ = forceContextType[Int] val reader = resource(new BufferedReader(new FileReader("test.txt"))) val writer = resource(new BufferedWriter(new FileWriter("test_copy.txt"))) var line = reader.readLine var count = 0 while(line != null) { count += 1 writer write line writer.newLine line = reader.readLine } count } </code></pre>
 

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