views:

87

answers:

1

Let's consider the following function:

def printPfType[T](pf:PartialFunction[T, _])(implicit m:Manifest[T]) = {
  println(m.toString)
}

Then I define the following test class:

case class Test(s:String, i:Int)

I can't write this:

printPfType {
  case Test(_,i) => i
}

because the compiler can't infer the first parametric type of the PartialFunction. I have to specify it explicitly:

printPfType[Test] {
  case Test(_,i) => i
}

But then the Test type appears twice. Is there a technique to avoid this? How can I help the type inferer to avoid the duplicate?

+5  A: 

See this thread. Type inference cannot handle this problem. Quote from the spec:

An anonymous function can be defined by a sequence of cases { case p1 => b1 . . . case pn => bn } which appear as an expression without a prior match. The expected type of such an expression must in part be defined. It must be either scala.Functionk[S1, . . . , Sk, R] for some k > 0, or scala.PartialFunction[S1, R], where the argument type(s) S1, . . . , Sk must be fully determined, but the result type R may be undetermined.

Vasil Remeniuk
Thanks a lot. The spec is clear !
asayn
You're welcome :)
Vasil Remeniuk