Scala,直接从超级构造函数调用中调用实例方法?
假设我有以下 Scala 代码:
class Foo(a: Int)
class Bar(b: Buffer[Int]) extends Foo (sum) {
def sum = (1 /: b)(_ + _)
}
为什么它会抱怨从构造函数调用方法 sum
?难道用这么简单的实现就不可能得到这样的行为吗?我意识到我可以为 Bar
创建一个伴随对象,但这并不完全是我会做的事情?
PS 没有“超级构造函数”标签!)))
更新:有哪些可能的替代方案?
Suppose I have the following Scala code:
class Foo(a: Int)
class Bar(b: Buffer[Int]) extends Foo (sum) {
def sum = (1 /: b)(_ + _)
}
why does it complain on calling the method sum
from the constructor? Is it not possible to get such a behavior with such simple implementation at all? I realize that I could make a companion object for Bar
but that is not exactlywhat would I do?
PS there is no 'superconstructor' tag!)))
UPDATE: What are possible alternatives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每次构造
Bar
实例时,它的所有成员都会添加到其中。只有构建完成后才能调用其成员。Each time an instance of
Bar
is being constructed all its members are being added to it. Only after the construction is complete can you call its members.如果
sum
没有在Bar
实例上被调用——事实上它没有被调用,因为它还没有被构造! -- 那么它的位置肯定不在Bar
内。如果Bar
是它的唯一用户,那么它的自然位置就是伴随对象。更有趣的问题是为什么你不希望它处于自然的位置?
if
sum
is not being called on aBar
instance -- and it isn't, since it hasn't been constructed yet! -- then its place is definitely not insideBar
. IfBar
is its sole user, then the natural place for it is the companion object.The more interesting question is why you don't want it in its natural place?