【问题标题】:Is there an implicit unlift of total functions in Scala when `PartialFunction` is required?当需要“PartialFunction”时,Scala 中的总函数是否存在隐式解除?
【发布时间】:2018-04-19 04:06:22
【问题描述】:

我对这个错误有点困惑

[error]  found   : A => B
[error]  required: PartialFunction[A,B]

我可以通过将我正在使用的函数包装在 Function.unlift(x => Some(...)) 中来修复它,但这似乎是我期望在 the doc's definition 中隐含的“PartialFunction[A, B] 类型的部分函数是一元函数,其中域不一定包含所有“A”类型的值。

对于“必然”这个词,这个定义似乎明确地包含了一个函数A => B 是一个PartialFunction[A, B]。我是不是看错了,还是漏掉了什么?

让我更加困惑的是,虽然我在使用 Throwablecom.twitter.util.Future[com.twitter.finagle.http.Response] 的代码中收到此错误,但我无法使用 a simpler example 重现它。

【问题讨论】:

    标签: scala


    【解决方案1】:

    PartialFunction does not necessarily include all values of type A 这意味着您只能处理目标值,而不能处理其他值。比如模式匹配

    示例 1:

    List(1, 2, 3, 4, 5).collect({
        case x if x % 2 == 0 => x + 1
    })
    

    在上面的代码sn-p中,我们只想处理偶数加号 1.如果没有PartialFunction,就需要@首先是987654324@偶数,然后是map

    示例 2:

    List(1, 2, "one", "two").collect({
        case x: String => x + 1
    })
    

    在示例 2 中,我们只想处理列表中的 String 类型值,因此 PartialFunction 也可以用于 匹配 类型。

    因此,如果您想将implicit 转换为FunctionPartialFunction,我认为您可以定义如下隐式方法:

      implicit def convertFunctionToPartialFunction[A, B](f: A => Option[B]) = {
        Function.unlift(f)
      }
      val a: Int => Option[Int] = (x: Int) => {
        if (x % 2 == 0) {
          Some(x + 1)
        } else None
      }
    
      val res = List(1, 2, 3, 4, 5).collect(a)
    

    但似乎a Function 很丑……

    【讨论】:

      【解决方案2】:

      PartialFunction[A, B]A => B 的子类型。特别是,它有 isDefinedAt 的方法 A => B 没有。因此,在预期 PartialFunction 的地方,无法使用正常功能。

      您的“更简单的示例”恰恰相反:它将PartialFunction 传递给需要函数的东西。这个方向很好用。

      不要乱用Function.unlift,你可以直接使用

      { case x => f(x) }
      

      (因为 PartialFunction 在您的情况下是预期的类型)。还有PartialFunction(f), but it's deprecated since 2.12.5

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-29
        • 1970-01-01
        • 1970-01-01
        • 2015-05-22
        • 2013-04-13
        • 2016-08-02
        相关资源
        最近更新 更多