scala 中具有私有构造函数和工厂的类?
如何在 Scala 中实现具有私有构造函数和静态创建方法的类?
以下是我目前在 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
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所写内容的直接翻译看起来像这样,
但这是一种有点非 Scalaish 的解决问题的方法,因为您正在创建一个未初始化的树,使用起来可能不安全,并将其传递给各种其他方法。相反,更规范的代码将具有丰富的(但隐藏的)构造函数:
如果可以以这种方式构造的话。 (在这种情况下取决于
Node
的结构。如果Node
必须引用父树,那么这可能不起作用或者会更加尴尬。如果Node
不需要知道,那么这将是首选样式。)The direct translation of what you wrote would look like
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:
if it's possible to construct that way. (Depends on the structure of
Node
in this case. IfNode
must have references to the parent tree, then this is likely to either not work or be a lot more awkward. IfNode
need not know, then this would be the preferred style.)