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

覆盖Scala中重复的类参数?

发布时间:2020-12-16 19:17:30 所属栏目:安全 来源:网络整理
导读:Scala语言规范版本2.8的4.6.2节描述了重复的参数,并说: The last value parameter of a parameter section may be suffixed by “*”,e.g. (…,x:T*). The type of such a repeated parameter inside the method is then the sequence type scala.Seq[T].
Scala语言规范版本2.8的4.6.2节描述了重复的参数,并说:

The last value parameter of a parameter section may be suffixed by “*”,e.g. (…,x:T*). The type of such a repeated parameter inside the method is then the sequence type scala.Seq[T].

但是,这段代码:

abstract class A { def aSeq : Seq[A] }
class B(val aSeq : A*) extends A
class C extends B { override val aSeq :Seq[A] = Seq() }

编译时出错:

overriding value aSeq in class B of type A*;  value aSeq has incompatible type

编译器似乎表明A *是来自Seq [A]的不同类型.

在这种情况下调查aSeq的实际类显示它是scala.collection.mutable.WrappedArray $ofRef的一个实例,但即使以下代码也无法使用相同的消息进行编译:

class C extends B { override val aSeq  = new ofRef(Array[A]()) }

所以问题是,如何覆盖由类上重复参数定义的成员?

如果您想知道它来自何处,那就是scala.xml.Elem在scala.xml.Node中覆盖子方法所做的事情.

解决方法

您的问题可归纳为:

scala> class A { def aSeq(i: Int*) = 1 }
defined class A

scala> class B extends A { override def aSeq(i: Seq[Int]) = 2 }
<console>:6: error: method aSeq overrides nothing
       class B extends A { override def aSeq(i: Seq[Int]) = 2 }

方法有不同的类型.规范说(强调我的):

The type of such a repeated parameter inside the method is then the sequence type scala.Seq[T]

由于Int *和Seq [Int]不在方法内,因此该特定句子不适用.

有趣的是,以下代码显示这些方法在擦除之前有不同的类型,但之后相同:

scala> class G { def aSeq(i:Int*) = 1; def aSeq(i:Seq[Int]) = 2 }
<console>:5: error: double definition:
method aSeq:(i: Seq[Int])Int and
method aSeq:(i: Int*)Int at line 5
have same type after erasure: (i: Seq)Int
       class G { def aSeq(i:Int*) = 1; def aSeq(i:Seq[Int]) = 2 }

那么问题就变成了,为什么你的B类可以扩展你的A抽象类.那里的规范可能存在不一致.我不知道…

编辑:我重新阅读规范,我无法弄清楚是否有任何与重复参数和覆盖相关的内容.似乎没有任何关于重复参数的返回类型,这是你获得的val aSeq访问器方法.

我认为Mark的答案是一种非常有效的方法.如果您无法关注它,您可以使用以下解决方法:

class C extends B {
  private def aSeqHelper(a: A*) = a
  override val aSeq = aSeqHelper(Seq[A](): _*)
}

例如:

import scala.xml._
class ElemX extends Elem("pref","label",<xml a="b"/>.attributes,TopScope) {
  private def childHelper(c: Node*) = c
  override val child = childHelper(<foo/><bar/>: _*) }

然后:

scala> new ElemX
res4: ElemX = <pref:label a="b"><foo></foo><bar></bar></pref:label>

(编辑:李大同)

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

    推荐文章
      热点阅读