加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用partial-function-parameter方法的基类型的Scala值类编译失

发布时间:2020-12-16 10:04:27 所属栏目:安全 来源:网络整理
导读:比如说,我定义了一个值类,如下所示 package object p { class ValueClass[T](val o: Option[T]) extends AnyVal { def foo: Option[T] = o collect { case t = t } }} 编译失败并显示以下消息: overriding method applyOrElse in trait PartialFunction of
比如说,我定义了一个值类,如下所示

package object p {
  class ValueClass[T](val o: Option[T]) extends AnyVal {
    def foo: Option[T] =
      o collect {
        case t => t
      }
  }
}

编译失败并显示以下消息:

overriding method applyOrElse in trait PartialFunction of type [A1 <: T,B1 >: T](x: A1,default: A1 => B1)B1;
  method applyOrElse has incompatible type
       o collect {
                 ^

错误消息对我来说似乎没那么有意义,好像我用map替换了collect(它需要一个函数而不是一个部分函数),或者类没有扩展AnyVal,代码片段会编译.

有谁可以解释背后的原因或链接到提交的问题?

解决方法

这是一个很好的.它的工作原理是2.11.0-M8,至少.

显然,

https://issues.scala-lang.org/browse/SI-8011

与完全匹配

https://issues.scala-lang.org/browse/SI-8018

在2.10.x,

scala> trait X[A] { def pf: PartialFunction[A,A] = { case a => a } }
defined trait X

scala> class X[A](val x: A) extends AnyVal { def pf: PartialFunction[A,A] = { case a => a } }
<console>:7: error: overriding method applyOrElse in trait PartialFunction of type [A1 <: A,B1 >: A](x: A1,default: A1 => B1)B1;
 method applyOrElse has incompatible type
       class X[A](val x: A) extends AnyVal { def pf: PartialFunction[A,A] = { case a => a } }
                                                                            ^

也许这个问题在2.10.3允许之后没有出现.

对于病态的好奇或空闲,以前有过:

https://issues.scala-lang.org/browse/SI-6482

https://issues.scala-lang.org/browse/SI-7022(重复)

https://issues.scala-lang.org/browse/SI-6187

好的,官方验证它实际上是一个好的.这是后端口被移植的提交:

commit ff9f60f420c090b6716c927ab0359b082f2299de
Author: Paul Phillips <paulp@improving.org>
Date:   Sat Oct 6 10:20:45 2012 -0700

    Fix for SI-6482,lost bounds in extension methods.

    That was a good one. How to create a new method with type
    parameters from multiple sources,herein.

更新显示2.11.0-M8做了一些事情:

apm@mara:~/goof$scalam
Welcome to Scala version 2.11.0-M8 (OpenJDK 64-Bit Server VM,Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class X[A](val x: A) extends AnyVal { def pf: PartialFunction[A,A] = { case a => a } }
defined class X

scala> :pa -raw
// Entering paste mode (ctrl-D to finish)

package object p {
  class ValueClass[T](val o: Option[T]) extends AnyVal {
    def foo: Option[T] =
      o collect {
        case t => t
      }
  }
}

// Exiting paste mode,now interpreting.


scala> new p.ValueClass(Some(7)).foo
res0: Option[Int] = Some(7)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读