Scala 中的 PartialFunction 类型推断 [英] PartialFunction type inference in Scala
问题描述
让我们考虑以下函数:
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)
我不会写这个:
printPfType {
case Test(_,i) => i
}
因为编译器无法推断 PartialFunction 的第一个参数类型.我必须明确指定它:
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
}
但是随后 Test
类型出现了两次.有没有一种技术可以避免这种情况?如何帮助类型推断器避免重复?
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:
可以定义匿名函数由一系列案例 { 案例 p1=> b1...case pn => bn } 显示为没有 a 的表达式之前的比赛.此类的预期类型必须部分定义表达式.它必须是 scala.Functionk[S1,..., Sk, R] 对于某些 k > 0,或scala.PartialFunction[S1, R],其中参数类型 S1, ..., SK必须完全确定,但结果类型 R 可能不确定.
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.
这篇关于Scala 中的 PartialFunction 类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!