Sean Connolly
Sean Connolly

Reputation: 5801

Reference Scala constructor args in default value

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?

Upvotes: 3

Views: 277

Answers (2)

tuxdna
tuxdna

Reputation: 8487

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))

Upvotes: 2

Dimitri
Dimitri

Reputation: 1786

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))
}

Upvotes: 5

Related Questions