Note that there are some explanatory texts on larger screens.

plurals
  1. PO.with alternative in scala
    primarykey
    data
    text
    <p>I come from Groovy and it has a <code>.with</code> method on every type which accepts a single-argument closure; the argument is the object on which the <code>.with</code> method is being called. This allows a very cool technique of extending the functional chaining capabilities, which releases you from obligation to introduce temporary variables, factors your code, makes it easier to read and does other niceties.</p> <p>I want to be able to do something like this:</p> <pre><code>Seq(1, 2, 3, 4, 5) .filter(_ % 2 == 0) .with(it =&gt; if (!it.isEmpty) println(it)) </code></pre> <p>Instead of</p> <pre><code>val yetAnotherMeaninglessNameForTemporaryVariable = Seq(1, 2, 3, 4, 5).filter(_ % 2 == 0) if (!yetAnotherMeaninglessNameForTemporaryVariable.isEmpty) println(yetAnotherMeaninglessNameForTemporaryVariable) </code></pre> <p>In other words in the first example the <code>.with</code> is kinda similar to <code>.foreach</code> but instead of iterating thru the items of the object it is being called once on the object itself. So <code>it</code> is equal to <code>Seq(1, 2, 3, 4, 5).filter(_ % 2 == 0)</code>.</p> <p>Since I was very surprised not to find anything like that in Scala, my questions are:</p> <ul> <li>am I missing something? </li> <li>are there any alternative techniques native to Scala? </li> <li>if not, are there any decent reasons why this feature is not implemented in Scala?</li> </ul> <p><strong>Update:</strong> An appropriate feature request has been posted on the Scala issue tracker: <a href="https://issues.scala-lang.org/browse/SI-5324" rel="nofollow">https://issues.scala-lang.org/browse/SI-5324</a>. Please vote and promote</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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