简体   繁体   中英

Class with private constructor and factory in scala?

How do I implement a class with a private constructor, and a static create method in Scala?

Here is how I currently do it in Java:

public class Tree {
    private Node root;

    /** Private constructor */
    private Tree() {}

    public static Tree create(List<Data2D> data) {
        Tree tree = new Tree();
        return buildTree(tree, data);//do stuff to build tree
    }

The direct translation of what you wrote would look like

class Tree private () {
  private var root: Node = null
}
object Tree { 
  def create(data: List[Data2D]) = {
    val tree = new Tree()
    buildTree(tree,data)
    tree
  }
}

but this is a somewhat un-Scalaish way to approach the problem, since you are creating an uninitialized tree which is potentially unsafe to use, and passing it around to various other methods. Instead, the more canonical code would have a rich (but hidden) constructor:

class Tree private (val root: Node) { }
object Tree {
  def create(data: List[Data2D]) = {
    new Tree( buildNodesFrom(data) )
  }
}

if it's possible to construct that way. (Depends on the structure of Node in this case. If Node must have references to the parent tree, then this is likely to either not work or be a lot more awkward. If Node need not know, then this would be the preferred style.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM