Core_Dumped
Core_Dumped

Reputation: 4699

Scala importing a file in all files of a package

I need to use an implicit ordering that has been defined in an object in a file

abc

in the following way:

object abc{
implicit def localTimeOrdering: Ordering[LocalDate] = Ordering.fromLessThan(_.isBefore(_))
}

So, I make a package object

xyz

inside a file 'package.scala' that in turn is in the package 'xyz' that has files in which I need the implicit ordering to be applicable. I write something like this:

package object xyz{
import abc._
}

It does not seem to work. If I manually write the implicit definition statement inside the package object, it works perfectly. What is the correct way to import the object (abc) such that all of its objects/classes/definitions can be used in my entire package 'xyz' ?

Upvotes: 1

Views: 369

Answers (1)

flavian
flavian

Reputation: 28511

You cannot import the implicit conversions in that way, you will have to:

Manually write them inside the object:

package obj {
   implicit def etc//
}

Or obtain them via inheritance/mixins:

package obj extends SomeClassOrTraitWithImplicits with AnotherTraitWithImplicits {
}

For this reason, you usually define your implicit conversions in traits or class definitions, that way you can do bulk import with a single package object.

The usual pattern is to define a helper trait for each case.

trait SomeClass {
   // all the implicits here
}
object SomeClass extends SomeClass {}

Doing this would allow you to:

package object abc extends SomeClass with SomeOtherClass with AThirdClass {
// all implicits are now available in scope.
}

Upvotes: 3

Related Questions