Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

duplicate package objects in main and test

Tags:

scala

sbt

I have a package object defined in both main and the test code tree as shown below. When I execute the program with sbt run the one in the main code tree takes effect. Whereas when I run the test cases (sbt test) the package object defined in the test code tree takes effect. For eg

src/main/scala/com/example/package.scala

package object core {
  val foo = "Hello World"
}

src/test/scala/com/example/package.scala

package object core {
val foo = "Goodbye World"
}

on sbt run the value of com.example.core.foo is Hello World. on sbt test the value of com.example.core.foo is Goodbye World

Is this just a quirk of SBT or is it a well defined scala/sbt trait?. I currently use this behaviour for dependency injection by defining my module bindings for production and test in their corresponding package objects. This is an advisable approach?

like image 244
rogue-one Avatar asked Oct 30 '22 07:10

rogue-one


1 Answers

Scala looks for package objects in your current path, so it's a well defined behavior. Since your code in test and main resides in different places it finds different val foos.

The way you are using this mechanism is very similar to using implicits. General advice with implicits and implicit resolution is not to abuse it. I think in this case it's not the best way of providing dependencies.

You always have to consider what scope you are in - if you are using a class defined in main in test scope how do you use foo from main, and how do you use foo from test - whenever you need one or the other. You have to think already about how it will work and consider various scenarios. What if your test class is in a different package, which foo would you get, does it depend on where your tested class is declared?

Make dependency injection more explicit and don't spend mental cycles on it, or run a chance to get someone confused.

like image 170
yǝsʞǝla Avatar answered Nov 09 '22 17:11

yǝsʞǝla