使用蛋糕模式时初始化特征属性
Initializing a trait attribute while using the cake patern
是否可以在蛋糕图案的封闭特征中初始化属性?类似于早期初始化器的东西。例如:
object CakePatternInit {
trait A {
var prop: String = null
}
trait A1 extends A
trait B {
this: A =>
println(prop.toUpperCase) // I'd like here prop to be initialized already with "abc"
}
def main(args: Array[String]) {
val b = new B with A1
// how do I initialize prop here?
// can I write something like this:
// val b = new B with { prop = "abc" } A1
}
}
trait A {
def prop: String
}
trait A1 extends A
trait B {
this: A =>
println(prop.toUpperCase) // I'd like here prop to be initialized already with "abc"
}
val t = new B with A1 { def prop = "Hello"}
> HELLO
> t.prop
res22: String = Hello
将您的 prop
声明为方法,因为 scala 无法覆盖 var 的
有篇文章可以帮到您:cake pattern
是否可以在蛋糕图案的封闭特征中初始化属性?类似于早期初始化器的东西。例如:
object CakePatternInit {
trait A {
var prop: String = null
}
trait A1 extends A
trait B {
this: A =>
println(prop.toUpperCase) // I'd like here prop to be initialized already with "abc"
}
def main(args: Array[String]) {
val b = new B with A1
// how do I initialize prop here?
// can I write something like this:
// val b = new B with { prop = "abc" } A1
}
}
trait A {
def prop: String
}
trait A1 extends A
trait B {
this: A =>
println(prop.toUpperCase) // I'd like here prop to be initialized already with "abc"
}
val t = new B with A1 { def prop = "Hello"}
> HELLO
> t.prop
res22: String = Hello
将您的 prop
声明为方法,因为 scala 无法覆盖 var 的
有篇文章可以帮到您:cake pattern