在默认值中引用 Scala 构造函数参数

Sea*_*lly 3 constructor arguments scala

在下面的 Scala 代码中,编译器告诉我,not found: value x当我尝试更新y、引用x、另一个构造函数参数的默认值时。

class Foo(x: String, y: Bar = new Bar(x))

class Bar(a: String)
Run Code Online (Sandbox Code Playgroud)

我相信这种限制是有充分理由的。任何人都可以阐明并可能提供替代方法吗?

Dim*_*tri 5

作为替代方法:

class Foo(x: String, y: Bar)

class Bar(a: String)

object Foo {
  def apply(x: String) = new Foo(x, new Bar(x))
}
Run Code Online (Sandbox Code Playgroud)

另一个:

class Foo(x: String, y: Bar) {
  def this(x: String) = this(x, new Bar(x))
}
Run Code Online (Sandbox Code Playgroud)