问题
In the following Scala code, the compiler is telling me not found: value x when I try to new up my default value for y, referencing x, another constructor argument.
class Foo(x: String, y: Bar = new Bar(x))
class Bar(a: String)
I trust there's good reason for this limitation. Can anyone shed some light and possibly offer an alternative approach?
回答1:
As an alternative approach:
class Foo(x: String, y: Bar)
class Bar(a: String)
object Foo {
def apply(x: String) = new Foo(x, new Bar(x))
}
Another one:
class Foo(x: String, y: Bar) {
def this(x: String) = this(x, new Bar(x))
}
回答2:
You are defining a class which has two members:
class Foo(x: String, y: Bar)
However when you bind y to a particular instance then effectively the class definition reduces to:
class Foo(x: String) { private val y = new Bar(x) }
Why? Since you are binding y to a Bar(x) instance, so no one should be able to change y without changing x.
Now if you notice the compiler is correct in saying not found: value x because x as an instance is only visible within constructor body. The same is true for y. Which means new Bar(x) in the following code would be called before the constructor is actually called and x and y parameters are materialized:
class Foo(x: String, y: Bar = new Bar(x))
来源:https://stackoverflow.com/questions/21508939/reference-scala-constructor-args-in-default-value