Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your unapply method could not be used in pattern matching </p> <p>It works with </p> <pre><code>def unapply(arg: &lt;type to match&gt;) : Option[(&lt;matched fields types&gt;)] </code></pre> <p>(no tuple if only one field, boolean instead than Option if no field).</p> <p>The standard unapply of User would be (The Scala Language Specification p. 67)</p> <pre><code>def unapply(u: User) = if (u eq null) None else Some((u.id, u.name)) </code></pre> <p>It what you want is to match a user with a zero id as in</p> <pre><code>user match {case User(name) =&gt; ....} </code></pre> <p>that would be</p> <pre><code>def unapply(u: User): Option[String] = if(u eq null || u.id != 0) None else Some(u.name) </code></pre> <p>If you want that a string can match as a User (this would be rather bizarre)</p> <pre><code>def unapply(s: String): Option[User] = Some(User(0, s)) </code></pre> <p>It would work with</p> <pre><code>"john" match case User(u) =&gt; ... // u is User(0, john) </code></pre> <p>I guess you want the former one. In which case both your apply and the standard one are two methods with the same argument list (one User parameter), so they are not compatible. This may be seen as a little unfortunate, as when methods are called as extractors, the distinguishing element is actually the size of the result tuple, not the type of the arguments. </p> <p>Your method however, while not valid as an extractor, causes no conflict. I could not find something in the spec that would forbid it. Still, it is useless and a useful method would rightly not be allowed. </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