Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class with private constructor and factory in scala?

Tags:

java

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
    }
like image 697
Andriy Drozdyuk Avatar asked Feb 13 '11 00:02

Andriy Drozdyuk


1 Answers

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

like image 66
Rex Kerr Avatar answered Sep 30 '22 06:09

Rex Kerr