在 Scala 中,构造函数如何引用它正在创建的对象? [英] In Scala, how can a constructor refer to the object it is creating?

查看:39
本文介绍了在 Scala 中,构造函数如何引用它正在创建的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Scala 中实现一个基于原型的系统.类型层次结构的根是 ROOT 节点,它有一个引用自身的原型.

I want to implement a prototype-based system in Scala. At the root of the type hierarchy is the ROOT node, which has a prototype that refers to itself.

以下代码演示了我正在尝试执行的操作:

The following code demonstrates what I'm trying to do:

class Node(val prototype: Node) {
    private def this() = this(this)
}

object Node {
    val ROOT = new Node
}

不幸的是,这不会编译错误:只能在类、对象或模板中使用".

Unfortunately, this does not compile an error: "this can only be used in a class, object, or template".

不接受调用主构造函数的参数this".这听起来很合理,因为对象尚未创建.但是,由于原型是不可变的,我不能将其设置为 null 并在之后定义它.

The argument "this" for the call to the primary constructor is not accepted. This sounds reasonable, since the object is not yet created. However, since prototype is immutable, I can't set it to null and define it afterwards.

有关如何在 Scala 中正确执行此操作的任何建议?

Any suggestions on how to do this properly in Scala?

我使用的是 Scala-2.8.0RC7.

I'm using Scala-2.8.0RC7.

推荐答案

您还可以执行以下操作.也许它不是最惯用的 Scala 代码,但它很短,我认为它可以回答您的问题.

You could also do the following. Maybe it is not the most idiomatic Scala code but it is short and I think it answers your question.

class Node(prot: Option[Node] = None) { def prototype = prot getOrElse this }

这篇关于在 Scala 中,构造函数如何引用它正在创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆