在下面的 Scala 代码中,编译器告诉我 not found: value x
当我尝试更新 y
的默认值时,引用 x
,另一个构造函数参数。
class Foo(x: String, y: Bar = new Bar(x))
class Bar(a: String)
我相信这种限制是有充分理由的。任何人都可以阐明一些想法并可能提供替代方法吗?
最佳答案
作为替代方法:
class Foo(x: String, y: Bar)
class Bar(a: String)
object Foo {
def apply(x: String) = new Foo(x, new Bar(x))
}
另一个:
class Foo(x: String, y: Bar) {
def this(x: String) = this(x, new Bar(x))
}
关于scala - 在默认值中引用 Scala 构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21508939/