n+2 } res52: List[Int] = List(3) 这很好用: scala> v-6ren">
gpt4 book ai didi

scala - 如何输入匿名 PartialFunction

转载 作者:行者123 更新时间:2023-12-05 01:04:21 24 4
gpt4 key购买 nike

这有效:

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 s。您可以通过注释它们的类型直接执行此操作:

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

注意 collect右边的表达式是必须的在括号内。

如果您不喜欢它的冗长,并且不介意让任何试图理解您的代码的人感到沮丧,您可以在 PartialFunction 上定义一个标识函数。 s 输入类型为 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>

关于scala - 如何输入匿名 PartialFunction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23412523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com