将 PartialFunction 与常规函数结合

编程入门 行业动态 更新时间:2024-10-12 12:24:46
本文介绍了将 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 与常规函数结合

本文发布于:2023-10-28 04:45:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535562.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   常规   PartialFunction

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!