【问题标题】:this.type as a constructor argumentthis.type 作为构造函数参数
【发布时间】:2013-04-09 21:43:38
【问题描述】:

从这个问题Why cannot this.type be used for new instances 开始。我想在构造函数中有一个 this.type 对象。我不相信可以做到这一点,但是我希望这里有人知道方法!
这是我的基本特征

trait Node {
  def parent:Option[this.type]
}

我已经实现了一个类如下

case class NodeInstance(parentValue:Option[NodeInstance]) extends Node {
  def parent = parentValue.asInstanceOf[Option[this.type]]
}

但我想拥有

case class NodeInstance(parent:Option[NodeInstance]) extends Node

但这给了一个覆盖方法 parent 有不兼容的类型异常。

我想我不能将 this 作为继承 NodeInstance 的对象(如果它是一个类的话),会破坏 this.type 要求。不过我想我会检查一下是否有更好的方法来解决这个问题......

如果我现在使用

trait Node[T] { self:T =>
  def parent:Option[T]
}

如果我将它嵌入到特征中,我想要一个返回根节点的函数“root”

trait Node[T] { self:T =>
  def parent:Option[T]
  def root:T = this.parent.map(_.root).getOrElse(this)
}

然后我得到编译器异常值 root is not a member of type Parameter T

如果我抽象出根,我会得到 T 的类型参数问题

object Node {
  def root[T <: Node[?]](node:T):T = node.parent.map(root(_)).getOrElse(this)
}

好的,刚刚发现我可以有 [T <: node>

【问题讨论】:

    标签: scala generics types


    【解决方案1】:

    this.type 指的是实例类型。由于您在构造函数中,因此无法确定this.type。你会得到错误:this can be used only in a class, object, or template

    在这些情况下,通常会引入类型参数和自身类型

    trait Node[T] { self:T =>
      def parent: Option[T]
    }
    
    case class NodeInstance(parent:Option[NodeInstance]) extends Node[NodeInstance]
    

    【讨论】:

    • 值得补充的是,this.type 应该只在我们谈论同一个对象时使用,this(例如,在可链接的 setter 中返回 this 时),并且不应该t 用于表示“与this 相同类型的其他对象”。
    • 在这种情况下,假设我创建了一个函数 def getAncestors[T <: node>
    • @JPullar def getAncestors[T &lt;: Node[T]](node:T):List[T] 有什么问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多