Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does the empty string not match as Seq.empty?
    text
    copied!<p><strong>EDIT: This was an old bug long since fixed in Scala 2.8 and later</strong></p> <p>During some experimentation around question <a href="https://stackoverflow.com/questions/740563/pattern-matching-a-string-as-seqchar">Pattern matching a String as Seq[Char]</a>, I ran across another weird matching phenomenon. Consider the following code that treats a string as a sequence of characters:</p> <pre><code>def %%&amp;#(input: String) : String = { val uha : Seq[Char] = input uha match { case Seq() =&gt; "Empty" case Seq(first @ _, 'o', 'o') =&gt; "Bar" case _ =&gt; "Oh" } } </code></pre> <p>Calling input on the empty String <code>""</code> correctly yields <code>"Empty"</code>.</p> <p>However, if I rewrite the first match clause as </p> <pre><code>case Seq.empty =&gt; "Empty" </code></pre> <p>the matching of <code>""</code> fails and matches the default clause instead.</p> <p>Walking through the Scala library source code (which you shouldn't have to do in an ideal world :-) ) I believe that both <code>Seq()</code> and <code>Seq.empty</code> will result in <code>RandomAccessSeq.empty</code>. Apparently, this does not concur with the phenomenon described above because only <code>Seq()</code> matches the empty String. </p> <p>UPDATE: Upon some further experimentation this question can be narrowed down to the following: </p> <pre><code>val list = List() &gt;&gt;&gt; list2: List[Nothing] = List() val emptySeq = Seq.empty list == emptySeq &gt;&gt;&gt; res1: Boolean = false </code></pre> <p>This basically means that an empty <code>Seq</code> does not automatically equal <code>Seq.empty</code> . So when matching against a constant (as opposed to using an extractor as suggested by starblue) this unequality leads to the failing match. The same is true when interpreting the empty <code>String</code> as a sequence.</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