Note that there are some explanatory texts on larger screens.

plurals
  1. POconditional loop conversion in Scala
    text
    copied!<p>I'd like to convert a piece of Java code which looks like the following into Scala:</p> <pre><code>for (Iterator&lt;Task&gt; it = tasks.iterator(); it.hasNext() &amp;&amp; workflow.isAutoRun();) { Task task = it.next(); if (!runTask(task)) break; } </code></pre> <p>I am not a fan of the scala <code>for-</code>comprehensions (not that I know how to <em>break</em> the iteration anyway) and I've come up with the following:</p> <pre><code>val completed = tasks.forall { task =&gt; workflow.isAutoRun &amp;&amp; runTask(task) } </code></pre> <p>However, the scaladoc for the <code>forall</code> method looks like the following (italics mine):</p> <blockquote> <p>Apply a predicate <code>p</code> <em>to all elements</em> of this iterable object and return true, iff the predicate yields true for all elements</p> </blockquote> <p>This is not equivalent to what I have done (because it implies that the predicate will be evaluated for each item, regardless of whether a previous evaluation has returned <code>false</code>) and (in fact) not actually equivalent to what the <code>forall</code> method actually does, which on <code>Iterator</code> looks like:</p> <pre><code> def forall(p: A =&gt; Boolean): Boolean = { var res = true while (res &amp;&amp; hasNext) res = p(next) res } </code></pre> <p>Anyway, I digress: has anyone got any better suggestions for what the scala code should look like? I want to see something which conveys the intent better:</p> <blockquote> <p><code>tasks.doUntil(t =&gt; !isAutoRun || !runTask(t))</code></p> </blockquote>
 

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