这有效:
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 " }
我不完全理解为什么推理失败,但是我可以猜测。重要的问题:如何解决?
最佳答案
您需要告诉编译器匿名PartialFunction
的参数类型。您可以通过注释其类型直接执行此操作:
List(1, "aa") collect ({
{ case n : Int => n+2 }: PartialFunction[Any, _]
} orElse {
{ case n : String => n + " plus two " }: PartialFunction[Any, _]
})
请注意,必须将表达式括在
collect
右边的括号中。如果您不喜欢那么冗长的代码,并且不介意让试图理解您的代码的人感到沮丧,则可以在
PartialFunction
上定义一个输入函数为Any
的身份函数: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 " }
)
您甚至可以拿出一个适当的怪异名称,并假装这是一种Scala语言功能:
def @:[T](f: PartialFunction[Any, T]): PartialFunction[Any, T] = f
scala> @:{case x: Int => x + 3}
res29: PartialFunction[Any,Int] = <function1>