将 PartialFunction 与常规函数结合 [英] Combine a PartialFunction with a regular function

查看:44
本文介绍了将 PartialFunction 与常规函数结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,假设我想为 PartialFunction 提供一个全能"后备:

So, suppose, I want to provide a "catch all" fall back for a PartialFunction:

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

这不会编译:缺少扩展函数的参数类型 ((x$1) => x$1.toString).这:

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

也不编译(同样的错误).

Does not compile either (same error).

这个:

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

类型不匹配而失败;发现:Int =>细绳;需要:PartialFunction[?,?]

我能找到的让它起作用的唯一方法是拼写整个事情:

The only way I could find to make it work is to spell out the whole thing:

val withDefault = foo orElse PartialFunction[Int, String] { _.toString }

有没有更好的语法?我的意思是,一个不必告诉它我正在将一个部分函数从 int 传递到 string 到它期望从 in 到 string 接收部分函数的地方.这一点都不含糊,我为什么要这样做?

Is there any better syntax for this? I mean, one without having to tell it that I am passing a partial function from int to string to where it expects to receive a partial function from in to string. This is not ambiguous at all, why do I have to do this?

推荐答案

也许你需要applyOrElse:

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

或者你可能想要这样的东西:

Or maybe you would like something like this:

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,您可以使用下一个语法:

Also if you want to get just another PartialFunction you can use the next syntax:

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

这篇关于将 PartialFunction 与常规函数结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆