开发者

PartialFunction type inference in Scala

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. 开发者_JS百科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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜