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

后端 未结 3 419
無奈伤痛
無奈伤痛 2021-01-06 13:06

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

The following

3条回答
  •  独厮守ぢ
    2021-01-06 13:21

    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)
    }
    

提交回复
热议问题