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
开发者_JAVA技巧 }
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.)
精彩评论