In Scala, how can a constructor refer to the object that it creates?

I want to implement a prototype based system in Scala. At the root of the type hierarchy is a ROOT node, which has a prototype that references itself.

The following code demonstrates what I'm trying to do:

class Node(val prototype: Node) {
    private def this() = this(this)
}

object Node {
    val ROOT = new Node
}

Unfortunately, this does not compile the error: "it can only be used in a class, object, or template."

The argument "this" for calling the main constructor is not accepted. This sounds reasonable since the object has not yet been created. However, since the prototype is immutable, I cannot set its value to null and determine it afterwards.

Any suggestions on how to do this correctly in Scala?

I am using Scala -2.8.0RC7.

+3
3

. , Scala, , , .

class Node(prot: Option[Node] = None) { def prototype = prot getOrElse this }
+2

, (Root- Simple-Nodes). ?

trait Node { def prototype: Node }

class RootNode extends Node { def prototype = this }

class SimpleNode(val prototype: Node) extends Node

REPL :

scala> val rootNode = new RootNode
rootNode: RootNode = RootNode@191dd1d

scala> val n1 = new SimpleNode(rootNode)
n1: SimpleNode = SimpleNode@30e4a7

scala> val n2 = new SimpleNode(n1)
n2: SimpleNode = SimpleNode@3a0589

scala> n2.prototype.prototype
res0: Node = RootNode@191dd1d

, , .

+7

, - node, ? , , Scala ( , )

, node null ( scala) Option?

class Node private[mypackage](val prototype : Option[Node]) {
  private def this() = this(None)
  private def this(ptype : Node) = this(Some(ptype)) //Public c-tor
}

object Node extends (Node => Node) {
  val Root = new Node
  def apply(ptype : Node) = new Node(ptype)
}
+1

Source: https://habr.com/ru/post/1752618/


All Articles