Private constructor class and factory in scala?

How to implement a class with a private constructor and a static create method in Scala?

This is how I do it now 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 } 
+4
source share
1 answer

A direct translation of what you wrote will 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 inconvenient way to approach the problem, since you are creating an uninitialized tree that is potentially unsafe to use, and passing it to other methods. Instead, more canonical code will have a rich (but hidden) constructor:

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

if possible. (Depends on the structure of Node in this case. If Node should have references to the parent tree, then this probably either will not work, or it will be much more inconvenient. If Node not necessary to know, this will be the preferred style.)

+9
source

Source: https://habr.com/ru/post/1339506/


All Articles