Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 472
Sean Connolly Avatar asked Apr 11 '26 19:04

Sean Connolly


2 Answers

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))
}
like image 124
Dimitri Avatar answered Apr 13 '26 08:04

Dimitri


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))
like image 30
tuxdna Avatar answered Apr 13 '26 09:04

tuxdna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!