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

scala – 可以覆盖类型字段吗?

发布时间:2020-12-16 09:11:59 所属栏目:安全 来源:网络整理
导读:scala class Cdefined class Cscala class subC extends Cdefined class subCscala class A { type T = C}defined class Ascala class subA extends A { override type T = subC}console:10: error: overriding type T in class A,which equals C; type T ha
scala> class C
defined class C

scala> class subC extends C
defined class subC

scala> class A { type T = C}
defined class A

scala> class subA extends A { override type T = subC}
<console>:10: error: overriding type T in class A,which equals C;
 type T has incompatible type
      class subA extends A { override type T = subC}
                                           ^

在上面的示例中,我收到一条错误消息,我不能覆盖类A中的类型字段(即使所选的类型subC扩展了类C).

是否可以覆盖一个类型字段?如果是,上面的例子有什么问题?

解决方法

你不会对类型说“超越”,而是缩小范围.

>类型T …无界限
>类型T <:C ... T是C或C的子类型(称为上限)
>类型T&gt ;:C … T是C或C的超类型(称为下限)
>类型T = C … T正好是C(类型别名)

因此,如果T是性状A的类型成员,并且SubA是A的子类型,则在(2)的情况下,SubA可以将T缩窄到更特定的子类型C,而在(3)的情况下,可以将其缩小到较高的超类型C.案件(1)不对SubA施加任何限制,而情况(4)意味着T是“最终”.

这对A中的T的可用性有影响,无论它是否可以作为方法参数的类型或方法的返回类型出现.

例:

trait C { def foo = () }
trait SubC extends C { def bar = () }

trait MayNarrow1 {
  type T <: C  // allows contravariant positions in MayNarrow1
  def m(t: T): Unit = t.foo  // ...like this
}

object Narrowed1 extends MayNarrow1 {
   type T = SubC
}

object Narrowed2 extends MayNarrow1 {
  type T = SubC
  override def m(t: T): Unit = t.bar
}

可以在MayNarrow1中定义方法m,因为类型T以逆向位置(作为方法参数的类型)发生,因此即使T在MayNarrow1的子类型中被缩小,它仍然有效(方法体可以像处理一样是C型).

相反,类型T = C不可避免地固定T,这将对应于使方法最终.通过固定T,它可以用于协变位置(作为方法的返回类型):

trait Fixed extends MayNarrow1 {
  type T = C   // make that T <: C to see that it won't compile
  final def test: T = new C {}
}

您现在可以轻松看到,必须禁止进一步“覆盖”T:

trait Impossible extends Fixed {
  override type T = SubC

  test.bar  // oops...
}

要完成,这里是较不常见的下限情况:

trait MayNarrow2 {
  type T >: SubC  // allows covariant positions in MayNarrow2
  def test: T = new SubC {}
}

object Narrowed3 extends MayNarrow2 {
  type T = C
  test.foo
}

object Narrowed4 extends MayNarrow2 {
  type T = C
  override def test: T = new C {}
}

(编辑:李大同)

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

    推荐文章
      热点阅读