实例化不可变的配对对象
是否可以创建一个具有对合作伙伴对象的不可变引用的类,或者它是否必须是我在创建后分配的 var
?
例如
class PairedObject (p: PairedObject, id: String) {
val partner: PairedObject = p // but I need ref to this object to create p!
}
或类似地,我如何实例化以下对?
class Chicken (e: Egg) {
val offspring = e
}
class Egg (c: Chicken) {
val mother = c
}
Is it possible to create a class with an immutable reference to a partner object, or does it have to be a var
that I assign after creation?
e.g.
class PairedObject (p: PairedObject, id: String) {
val partner: PairedObject = p // but I need ref to this object to create p!
}
or similarly how could I instantiate the following pair?
class Chicken (e: Egg) {
val offspring = e
}
class Egg (c: Chicken) {
val mother = c
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是鸡/蛋问题的完整解决方案:
请注意,您必须为
chicken
和egg
变量提供显式类型。对于配对对象:
Here is a complete solution to the Chicken/Egg problem:
Note that you have to provide explicit types to the
chicken
andegg
variables.And for PairedObject:
如果您的问题是循环引用,您可以使用此问题中发布的解决方案:
scala:创建对象时循环引用?
这解决了先有鸡还是先有蛋的问题。
If your problem is circular references, you could use the solution posted in this SO question:
scala: circular reference while creating object?
This solves the chicken/egg problem.