In Scala, how can a constructor refer to the object it is creating?

与世无争的帅哥 提交于 2019-12-01 00:37:02
Ruediger Keller

You could also do the following. Maybe it is not the most idiomatic Scala code but it is short and I think it answers your question.

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

For this looks like you have two kinds of things (Root- and Simple-Nodes) What about this?

trait Node { def prototype: Node }

class RootNode extends Node { def prototype = this }

class SimpleNode(val prototype: Node) extends Node

In the REPL you can do this then:

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

I don't know, if that is what you are looking for.

I don't quite see how you can do this - how can you have a constructed instance of the root node, if you need it to already exist when creating it? So the thing at fault here is your modelling of the problem domain, not Scala (or any other language for that matter)

Surely the root node could have a null prototype, or (more idiomatic scala) an Option prototype?

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)
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!