加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如何键入匿名PartialFunction

发布时间:2020-12-16 10:04:39 所属栏目:安全 来源:网络整理
导读:这有效: 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] = function1scala var g:PartialFunction[Any,String] =
这有效:

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 " }

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

解决方法

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

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

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

如果你不喜欢罗嗦,并且你不介意试图理解你的代码的人感到沮丧,你可以在PartialFunctions上定义一个输入类型为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] = f

scala> @:{case x: Int => x + 3}
res29: PartialFunction[Any,Int] = <function1>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读