1

Following on somewhat from this question Why cannot this.type be used for new instances . I want to have a this.type object in a constructor. I don't believe that this can be done, however I am hopeful some one here knows a way!
This is my base trait

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

and I have implemented a class as follows

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

but I would like to have had

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

But this gives an overriding method parent has incompatible type exception.

I imagine that I cannot have this as an object that inherited NodeInstance (if it was a class say), would break the this.type requirement. However I thought I would check to see if there exists a better way around this...

now if I use

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

And I want a function 'root' which returns the root node, if I embedded it in the trait

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

Then I get the compiler exception value root is not a member of type Parameter T

If I abstract out root, I then get type parameter issues for T

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

OK, just discovered I can have [T <: Node[T]]

1 Answer 1

3

this.type refers to the instance type. Since you are in the constructor there is no way to determine this.type. You will get the error: this can be used only in a class, object, or template.

In these situations it's common to introduce a type parameter and a self type

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

case class NodeInstance(parent:Option[NodeInstance]) extends Node[NodeInstance]
3
  • 1
    It is worth adding that this.type should only be used when we are talking about the very same object, this (e.g., when returning this in a chainable setter), and shouldn't be used to mean “some other object of the same type as this”. Apr 9, 2013 at 13:19
  • In this case say I create a function def getAncestors[T <: Node](node:T):List[T] I then have a recursive type parameter issue
    – J Pullar
    Apr 9, 2013 at 13:26
  • @JPullar what is wrong with def getAncestors[T <: Node[T]](node:T):List[T]?
    – EECOLOR
    Apr 9, 2013 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.