这样做是可行的:
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 " } 我不明白为什么推论失败,但我能猜到。重要的问题是:我如何解决它?
发布于 2014-05-01 19:14:20
您需要告诉编译器匿名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>https://stackoverflow.com/questions/23412523
复制相似问题