如何键入匿名PartialFunction

时间:2014-05-01 16:59:22

标签: scala

这有效:

scala> List(1, "aa") collect {  case n : Int => n+2 } 
res52: List[Int] = List(3)

这很好用:

scala> var f:PartialFunction[Any, Int] = { case n : Int => n+2 }
f: PartialFunction[Any,Int] = <function1>

scala> var g:PartialFunction[Any, String] = { case n : String => n + " plus two " }
g: PartialFunction[Any,String] = <function1>

scala> List(1, "aa") collect (f orElse g)
res51: List[Any] = List(3, "aa plus two ")

但是,如果我尝试将两者结合在一起,那么:

scala> List(1, "aa") collect { case n : Int => n+2 } orElse { case n : String => n + " plus two " } 
<console>:8: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: PartialFunction[?,?]
              List(1, "aa") collect { case n : Int => n+2 } orElse { case n : String => n + " plus two " } 

我不明白为什么推理会失败,但我可以猜到。重要的问题:我该如何解决?

1 个答案:

答案 0 :(得分:5)

您需要告诉编译器您的匿名PartialFunction的参数类型。您可以通过注释其类型直接执行此操作:

List(1, "aa") collect ({
  { case n : Int => n+2 }: PartialFunction[Any, _]
} orElse {
  { case n : String => n + " plus two " }: PartialFunction[Any, _]
})

请注意,必须将表达式括在括号中collect的右侧。

如果您不喜欢罗嗦,并且您不介意试图理解您的代码的人感到沮丧,您可以在PartialFunction上定义一个输入类型为{{1}的身份函数}:

Any

你甚至可以提出一个非常奇怪的名字并假装它是Scala语言功能:

def pfa[T](f: PartialFunction[Any, T]): PartialFunction[Any, T] = f

List(1, "aa") collect (
  pfa { case n : Int => n+2 }
  orElse pfa { case n : String => n + " plus two " }
)