Compiler forbids to match a generic object if type parameters are declared at the class level

287 views
Skip to first unread message

Piotr Kolaczkowski

unread,
Jun 22, 2014, 4:44:13 AM6/22/14
to scala...@googlegroups.com
scala> trait Token[T]
defined trait Token

scala> trait TokenFactory[V, T <: Token[V]]
defined trait TokenFactory

scala> object TF1 extends TokenFactory[Long, Token[Long]]
defined module TF1

scala> def checkTF[V, T <: Token[V]](tf: TokenFactory[V, T]) = tf match { case TF1 => "TF1"; case _ => "other" }
checkTF: [V, T <: Token[V]](tf: TokenFactory[V,T])Any

scala> checkTF(TF1)
res1: String = TF1    /

// Now the only difference is we put it in the class:

trait Foo[V, T <: Token[V]] {  def checkTF(tf: TokenFactory[V, T]) = tf match { case TF1 => "TF1"; case _ => "other" } }
<console>:12: error: pattern type is incompatible with expected type;
 found   : TF1.type
 required: TokenFactory[V,T]
Note: if you intended to match against the class, try `case _: <none>`
       trait Foo[V, T <: Token[V]] {  def checkTF(tf: TokenFactory[V, T]) = tf match { case TF1 => println("TF1"); case _ => "other" } }
                                                                                            ^

Why? I don't understand why the place of declatring the type parameters (class / method) changes pattern matching validity.

Thanks,
Piotr

Jason Zaugg

unread,
Jun 22, 2014, 5:20:10 PM6/22/14
to Piotr Kolaczkowski, scala-user, martin odersky
On Sun, Jun 22, 2014 at 10:44 AM, Piotr Kolaczkowski <pkol...@datastax.com> wrote:

Why? I don't understand why the place of declatring the type parameters (class / method) changes pattern matching validity.

The difference comes down to the way that pattern type inference replaces method type parameters (by using freeTypesOfTerms) with fresh type variables when checking of the pattern type and scrutinee type are compatible. 

I don't know the rationale for this. I've cc-ed Martin who might be able to help out.

-jason

martin odersky

unread,
Jun 23, 2014, 6:49:59 AM6/23/14
to Piotr Kolaczkowski, scala-user
On Sun, Jun 22, 2014 at 10:44 AM, Piotr Kolaczkowski <pkol...@datastax.com> wrote:
In the method case, what you have here is a GADT: Patterns determine the type parameters of an corresponding methods in the scope of a pattern case. GADTs are not available for class parameters.
As far as I know, nobody has yet explored this combination, and it looks like it would be quite tricky to get this right.

 - Martin


Thanks,
Piotr

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Martin Odersky
EPFL

Reply all
Reply to author
Forward
0 new messages