将PartialFunction与常规函数结合使用

时间:2016-07-13 17:01:27

标签: scala combinators partialfunction

所以,假设,我想提供一个"赶上所有"退回PartialFunction

 val foo: PartialFunction[Int, String] = { case 1 => "foo" }
 val withDefault = foo orElse { _.toString }

这不编译:{{1​​}}。 这个:

missing parameter type for expanded function ((x$1) => x$1.toString)

不编译(相同的错误)。

这:

  val withDefault = foo orElse { case x: Int => x.toString }

val withDefault = foo orElse { (x: Int) => x.toString }

失败

我能找到的唯一方法就是拼出整个事情:

type mismatch; found   : Int => String; required: PartialFunction[?,?]

这有更好的语法吗?我的意思是,一个没有必须告诉它我正在将一个部分函数从int传递到string,它希望从in到string接收一个部分函数。这根本不含糊,我为什么要这样做呢?

2 个答案:

答案 0 :(得分:2)

也许您需要applyOrElse

val withDefault = foo.applyOrElse(_: Int, (_: Int).toString)

或许你想要这样的东西:

implicit class PartialFunToFun[A,B](val f: PartialFunction[A,B]) extends AnyVal {
  def withDefault(bar: A => B) = f.applyOrElse[A,B](_: A, bar)
}

并使用它:foo.withDefault(_.toString)(1)

此外,如果您想获得另一个PartialFunction,您可以使用下一个语法:

val withDefault = foo.orElse[Int, String]{case x => x.toString}

答案 1 :(得分:0)

前两个遇到的错误并非特定于orElse。当您尝试单独定义相同的功能时,也会出现这种情况。

scala> { _.toString }
<console>:12: error: missing parameter type for expanded function ((x$1: <error>) => x$1.toString)
       { _.toString }


scala> { case x: Int => x.toString }
<console>:12: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?
       { case x: Int => x.toString }
       ^

对于最后一个,您定义的是函数而不是PartialFunction,因此导致“类型不匹配”,因为orElse期望传递PartialFunction。

scala> { (x: Int) => x.toString }
res3: Int => String = $$Lambda$1127/2044272973@3d5790ea

我要添加的最后一件事是orElse是一种结合两个PartialFunction的方法。 _.toString本身不是PartialFunction,但您可以创建一个使用它的PartialFunction。对我而言,听起来你想要为foo未定义的所有值都有一个“默认”结果,所以我认为你实际上想要applyOrElse,因为那是它的用例。 See the API to learn more.