scala 中具有私有构造函数和工厂的类?

发布于 2024-10-17 02:00:22 字数 346 浏览 0 评论 0原文

如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不喜欢何必死缠烂打 2024-10-24 02:00:22

您所写内容的直接翻译看起来像这样,

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

但这是一种有点非 Scalaish 的解决问题的方法,因为您正在创建一个未初始化的树,使用起来可能不安全,并将其传递给各种其他方法。相反,更规范的代码将具有丰富的(但隐藏的)构造函数:

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

如果可以以这种方式构造的话。 (在这种情况下取​​决于 Node 的结构。如果 Node 必须引用父树,那么这可能不起作用或者会更加尴尬。如果 Node 不需要知道,那么这将是首选样式。)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文