When I have a package object defined with implicit types in the same package where I intend to use I don’t have to write any explicit import statement, which is pretty convenient. However, if I have package object defined in any of other parent object then implicit lookup doesn’t go there unless I explicitly import that package object.
e.g.
Package Object:
package com.mycomp.myproj.myservice
package object dao {
implicit def toXyz(str: String): Xyz
}
Target Class 1:
package com.mycomp.myproj.myservice.dao
object test {
val xyz : Xyz = "str" //this works
}
Target Class 2:
package com.mycomp.myproj.myservice.**myrepo**
object test {
val xyz : Xyz = "str" //this doesn't works
}
Why wouldn’t implicit lookup go to the package object defined in parent packages? what harm it could have?
Implicit scope includes the package objects of enclosing packages. “implicits defined in a package object are part of the implicit scope of a type prefixed by that package.”
Not sure it makes sense to include arbitrary child package objects?
Reason I raised this question is I am ending up defining package object for each package since visibility of type defined in package object is limited to only that package and not its child package. It just look ugly to have a package object for each package (modules). Moreover it reduces code reusability. You end up having package object in each package to have it imported automatically. Package object seems to be designed for defining common type aliases, implicits, functions, fields etc. Writing explicit import statement to import such package object seems to defeating it’s purpose. I could just as well defined all that in regular object and import it.
So am I correct in saying if you define packages as
a.b.c.d
then you have to import package objects into each subpackage, whereas chained package clauses gets around this problem - but is considered bad style. If so, what is the best practice for package wide implicits etc? - I’m currently trying to share some common code but find I’m importing it into every file, so not really benefitting.
(I read that Dotty does away with package objects).