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

scala中的循环类型参数定义

发布时间:2020-12-16 18:25:15 所属栏目:安全 来源:网络整理
导读:我试图定义一个通用容器,其元素可以返回封闭容器.就像是: abstract class Container[E : Element] { // compile error def contains( e: E ): Boolean def addNewElement(): Unit}abstract class Element[C : Container] { // compile error def enclosingC
我试图定义一个通用容器,其元素可以返回封闭容器.就像是:

abstract class Container[E <: Element] { // compile error
  def contains( e: E ): Boolean
  def addNewElement(): Unit
}

abstract class Element[C <: Container] { // compile error
  def enclosingContainer(): C
}

class MyContainer extends Container[MyElement] {
  private var elements = List[MyElement]()
  override def contains( elem: MyElement ) = elements.contains( elem )
  override def addNewElement() { elements ::= new MyElement(this) }
}

class MyElement( container: MyContainer ) extends Element[MyContainer] {
  override val enclosingContainer = container
}

但是,该片段不能编译,因为我应该在抽象类Container [E<:Element]定义中给Element一个类型参数,在抽象类Element [C<:Container]定义中给一个Container类型. 我有办法实现我正在寻找的行为吗?容器和元素是否有适当的声明?我应该定义第三方对象吗?

解决方法

已经给出的其他解决方案无法强制类型匹配:也就是说,给定一个类型ContainerImpl扩展Container,您应该确保ContainerImpl.E.C应该是ContainerImpl而不是其他容器.这是一个强制执行此操作(改编自 http://programming-scala.labs.oreilly.com/ch13.html):

abstract class ContainerWithElement {
  type C <: Container
  type E <: Element

  trait Container {
    self: C =>
    def contains( e: E ): Boolean
    def addNewElement(): Unit
  }

  trait Element {
    self: E =>
    def enclosingContainer(): C
  }
}

(编辑:李大同)

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

    推荐文章
      热点阅读