Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy scala's pattern maching does not work in for loops for type matching?
    text
    copied!<p>I'm coding against an API that gives me access to remote file system. The API returns a list of files and directories as list of node objects (parent to file and directory). </p> <p>I want to work only on a directories, ignoring files. I've tried to use type pattern matching in <code>for</code> loop but it does not work:</p> <pre><code>for { dir: CSDir &lt;- workarea.getChildren() // &lt;-- I'm getting an error here complaining about type conversion } { println(dir) } </code></pre> <p>Here is a similar example using scala basic objects to run it without dependencies:</p> <pre><code>val listOfBaseObjects:List[Any] = List[Any]("a string", 1:Integer); for (x: String &lt;- listOfObjects) { println(x) } </code></pre> <p>I end up using a regular pattern matching in side of for loop and that works fine:</p> <pre><code>// This works fien for (child &lt;- workarea.getChildren()) { child match { case dir: CSDir =&gt; println(dir) case _ =&gt; println("do not nothing") } } </code></pre> <h2>Question:</h2> <p>Can you tell me why the first /second example does not work in scala 1.9?</p> <p>In the "Programming in Scala" the <code>for</code> loop is advertised to use the same pattern matching as the <code>match</code> so it should work.</p> <p>If the for and match are different it would be great if you could point me to some articles with more details. What about pattern matching in assignment?</p> <h2>Update:</h2> <p>I can't accept an answer that states that it is impossible to skip elements in for loop as this contradicts with the "Prog. in scala". Here is a fragment from section 23.1:</p> <blockquote> <p><code>pat &lt;- expr</code> ... The pattern <code>pat</code> gets matched one-by-one against all elements of that list. ... if the match fails, no MatchError is thrown. Instead, the element is simply discarded from the iteration</p> </blockquote> <p>and indeed the following example works just fine:</p> <pre><code>scala&gt; val list = List( (1,2), 1, 3, (3,4)) scala&gt; for ((x,y) &lt;- list) { println (x +","+ y) } 1,2 3,4 </code></pre> <p>Why then type matching does not work?</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