macwire icon indicating copy to clipboard operation
macwire copied to clipboard

Picking correct constructor

Open lxwbr opened this issue 9 years ago • 8 comments

I am using an external class Foo:

public Foo() {
}

public Foo(Bar bar) {
  this.bar = bar;
}

and trying to wire it in my Scala module:

// Dependancy
def Bar: bar

lazy val foo: Foo = wire[Foo]

Unfortunately MacWire picks the constructor without parameters, though the Bar dependancy is in scope. Is there any way except using the constructor itself to tell MacWire which one to pick?

lxwbr avatar Apr 21 '16 15:04 lxwbr

MacWire always uses the primary constructor - and that's currently hard-coded. I suspect that's a Java class that you are trying to wire? I'm afraid that in this case you'll have to resort to manual wiring

adamw avatar Apr 21 '16 15:04 adamw

@adamw yes, unfortunately it is a Java class. Out of curiosity - how would I solve the problem if it would be a Scala class?

lxwbr avatar Apr 21 '16 15:04 lxwbr

I think in Scala usually (at least from my experience) you have a single constructor or the constructor that you want to use is the primary one. That's just due to a different coding style in both langs

adamw avatar Apr 21 '16 15:04 adamw

@adamw you can define default parameters class Foo(bar: Bar, name: String = "default name"). But I guess an answer to this is the same as for the Java case.

lxwbr avatar Apr 21 '16 15:04 lxwbr

Actually, I'm not sure how MacWire would behave with default arguments. Something to test :)

adamw avatar Apr 21 '16 15:04 adamw

Here a quick test:

trait FoobarModule {
  lazy val foo = wire[Foo]
  lazy val specialName = "special name"
  lazy val bar = wire[Bar]
}
class Bar(foo: Foo, val name: String = "default name")
class Foo()

Calling foobarModule.bar.name yields "special name". Removing lazy val specialName = "special name" results in a compiler error. So basically MacWire can not deal with default values at all. I find this behaviour acceptable and am not sure how I would feel otherwise. So as it is I am pretty fine with the current solution.

If you also want to leave it as it is, feel free to close this issue. :)

lxwbr avatar Apr 28 '16 11:04 lxwbr

I think that it's fine as is now - taking into account default values could create confusion - but I'll leave the issue open for now if others would have other opinions. Thanks!

adamw avatar May 05 '16 12:05 adamw

I recently had a case when wiring a class with default parameter values in the constructor, and I also think the current behaviour is the right one (ignoring default value, forcing you to put one in scope)

Taking default values in account may bring a little bit of magic, I'm not sure how I would feel about that, explicit sounds better.

alexduf avatar Jun 15 '16 12:06 alexduf