Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To expand on the previous answer... for, foreach and map are all higher-order functions - they can all take a function as an argument, so starting here:</p> <pre><code>val list = List(1,2,3) list.foreach(i =&gt; println(i * 2)) </code></pre> <p>You have a number of ways that you can make the code more declarative in nature, and cleaner at the same time.</p> <p>First, you don't really need to use the name - <code>i</code> - for each member of the collection, you can use <code>_</code> as a placeholder instead:</p> <pre><code>list.foreach(println(_ * 2)) </code></pre> <p>You can also separate the logic out into a distinct method, and continue to use placeholder syntax:</p> <pre><code>def printTimesTwo(i:Int) = println(i * 2) list.foreach(printTimesTwo(_)) </code></pre> <p>Even cleaner, just pass the raw function without specifying parameters (<em>look ma, no placeholders!</em>)</p> <pre><code>list.foreach(printTimesTwo) </code></pre> <p>And to take it to a logical conclusion, this can be made cleaner still by using <em>infix</em> syntax. Which I show here working with a standard library method. <em>Note: you could even use a method imported from a java library, if you wanted</em>:</p> <pre><code>list foreach println </code></pre> <hr> <p>This thinking extends to anonymous functions and <em>partially-applied functions</em> and also to the map operation:</p> <pre><code>// "2 *" creates an anonymous function that will double its one-and-only argument list map { 2 * } </code></pre> <p>For-comprehensions aren't really very useful when working at this level, they just add boilerplate. But they do come into their own when working with deeper nested structures:</p> <pre><code>//a list of lists, print out all the numbers val grid = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9)) grid foreach { _ foreach println } //hmm, could get confusing for(line &lt;- grid; cell &lt;- line) println(cell) //that's clearer </code></pre> <p>I didn't need the <code>yield</code> keyword there, as nothing is being returned. But if I wanted to get back a list of Strings (un-nested):</p> <pre><code>for(line &lt;- grid; cell &lt;- line) yield { cell.toString } </code></pre> <p>With lots of generators, you'll want to split them over multiple lines:</p> <pre><code>for { listOfGrids &lt;- someMasterCollection grid &lt;- listOfGrids line &lt;- grid cell &lt;- line } yield { cell.toString } </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