使用 Scala 构造函数来设置 trait 中定义的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8178602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using scala constructor to set variable defined in trait
提问by Seba Kerckhof
If I understand correctly, traits are the closest thing to Java interfaces and class constructors automatically set the variables.
如果我理解正确的话,特征是最接近 Java 接口和类构造函数自动设置变量的东西。
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 的类,并且有一个从 trait 设置变量的构造函数,比如:
trait Foo {
var foo: String
}
class Bar (foo: String) extends Foo { /* ... */ }
Where I want the foostring of the trait been set when I make a Barobject.
foo当我创建一个Bar对象时,我希望在哪里设置特征的字符串。
The compiler seems to give me errors about this. What is the correct way to achieve this?
编译器似乎给了我关于这个的错误。实现这一目标的正确方法是什么?
采纳答案by Didier Dupont
Barmust define the abstract var fooin Foo(would be the same for a val). This can be done in the constructor
Bar必须定义抽象var foo的Foo(将是一个相同val)。这可以在构造函数中完成
class Bar(var foo: String) extends Foo{...}
(of course, it could be done in the body of Bartoo). By default, constructor parameters will be turned to private valif need be, that is if they are used outside the initiailization code, in methods. But you can force the behavior by marking them valor var, and possibly control the visibility as in
(当然,它也可以在 body 中完成Bar)。默认情况下,val如果需要,构造函数参数将变成私有的,也就是说,如果它们在初始化代码之外,在方法中使用。但是您可以通过标记它们val或来强制行为var,并可能控制可见性,如
class X(protected val s: String, private var i: Int)
Here you need a public varto implement Foo.
在这里你需要一个 publicvar来实现Foo.
回答by Rex Kerr
trait Foo { var foo: String = _ }
class Bar(foo0: String) extends Foo { foo = foo0 }
The trait declares an uninitialized var; the class then sets it equal to the input parameter.
trait 声明了一个未初始化的 var;然后类将它设置为等于输入参数。
Alternatively,
或者,
trait Foo {
def foo: String
def foo_=(s: String): Unit
}
class Bar(var foo: String) extends Foo {}
declares the getter/setter pair corresponding to a foo, which are set by the class.
声明对应于 foo 的 getter/setter 对,它们由类设置。

