使用scala构造函数设置trait中定义的变量
如果我理解正确的话,traits 是最接近 Java 接口的东西,类构造函数会自动设置变量。
但是,如果我有一个扩展特征的类,并且有一个从特征设置变量的构造函数,例如:
trait Foo {
var foo: String
}
class Bar (foo: String) extends Foo { /* ... */ }
当我创建 < 时,我希望设置特征的 foo
字符串,该 怎么办? code>Bar 对象。
编译器似乎给了我关于此的错误。实现这一目标的正确方法是什么?
If I understand correctly, traits are the closest thing to Java interfaces and class constructors automatically set the variables.
But what if I have a class that extends a trait and has a constructor which sets a variable from the trait, so something like:
trait Foo {
var foo: String
}
class Bar (foo: String) extends Foo { /* ... */ }
Where I want the foo
string of the trait been set when I make a Bar
object.
The compiler seems to give me errors about this. What is the correct way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该特征声明了一个未初始化的变量;然后该类将其设置为等于输入参数。
或者,
声明与 foo 相对应的 getter/setter 对,它们由类设置。
The trait declares an uninitialized var; the class then sets it equal to the input parameter.
Alternatively,
declares the getter/setter pair corresponding to a foo, which are set by the class.
Bar
必须在Foo
中定义抽象var foo
(与val
相同)。这可以在构造函数中完成(当然,也可以在
Bar
主体中完成)。默认情况下,如果需要的话,构造函数参数将被转换为私有val
,即如果它们在初始化代码之外的方法中使用。但是您可以通过标记它们val
或var
来强制执行该行为,并可能控制可见性,如这里您需要一个公共
var
来实现 <代码>Foo。Bar
must define the abstractvar foo
inFoo
(would be the same for aval
). This can be done in the constructor(of course, it could be done in the body of
Bar
too). By default, constructor parameters will be turned to privateval
if need be, that is if they are used outside the initiailization code, in methods. But you can force the behavior by marking themval
orvar
, and possibly control the visibility as inHere you need a public
var
to implementFoo
.