Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Quoting from Scala syntax rules:</p> <pre><code>varid ::= lower idrest idrest ::= {letter | digit} [‘_’ op] op ::= opchar {opchar} opchar ::= “all other characters in \u0020-007F and Unicode categories Sm, So except parentheses ([]) and periods” // 'a' and 'a_-' is valid, 'a(' is not. </code></pre> <p>Rule for Typed Pattern match says:</p> <pre><code>Pattern1 ::= varid ‘:’ TypePat | ‘_’ ‘:’ TypePat </code></pre> <p>So</p> <pre><code>def pr(list: Any) = list match { case a :String =&gt; // works case a_- :String =&gt; // works a_- is valid instance of 'varid' case a() :String =&gt; // does not work. case a(b) :List[Int] // does not work either! } </code></pre> <p>Hence:</p> <pre><code>case S(a): S[ta] is not valid syntax for pattern match. </code></pre> <p>However following is valid</p> <pre><code>case (s1 :S[a], s2: S[b]) </code></pre> <p>according to Tuple Pattern matching rule:</p> <pre><code>SimplePattern ::= ‘(’ [Patterns] ‘)’ Patterns ::= Pattern {‘,’ Patterns} </code></pre> <p>Apart from the two possible options that you have listed, you may also use:</p> <pre><code> case tup: (S[_], S[_]) =&gt; </code></pre> <p>Following seems to work:</p> <pre><code>trait T case class S[A](a: A, w: A =&gt; Int) extends T def makeTwo(t1: T, t2: T) = (t1, t2) match { case (S(a1, w1), S(a2, w2)) =&gt; val wNew = { tup:(Any, Any) =&gt; w1(tup._1) + w2(tup._2) } S((a1, a2), wNew) } def someString (s: String) = { s.length } val twoS = makeTwo(S("Hello", someString), S("World!", someString)) println(twoS.w(twoS.a)) // gives 11 </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