gpt4 book ai didi

scala - 匿名 PartialFunction 语法

转载 作者:行者123 更新时间:2023-12-01 06:06:29 26 4
gpt4 key购买 nike

我之前问过这个问题:Combine a PartialFunction with a regular function

然后意识到,我实际上并没有问对。
所以,这是另一个尝试。

如果我这样做:

 val foo = PartialFunction[Int, String] { case 1 => "foo" }
val bar = foo orElse { case x => x.toString }

它不编译: 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[?,?]

但这工作正常:
   val x: Seq[String] = List(1,2,3).collect { case x => x.toString }

问题是有什么区别?两种情况下参数的类型相同: PartialFunction[Int, String] .传入的值实际上是相同的。为什么一种情况有效,而另一种无效?

最佳答案

您需要为 bar 指定类型因为编译器无法推断它。这编译:

val foo = PartialFunction[Int, String] { case 1 => "foo" }
val bar : (Int => String) = foo orElse { case x => x.toString }

关于scala - 匿名 PartialFunction 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38359522/

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