TimY
TimY

Reputation: 5416

import to all package member files (package scope)

I have multiple class files in one package/directory. Similar to this:

File 1:

package model
import same.library
class File1Class {}[...]

File 2:

package model
import same.library
class File2Class {}[...]

etc...

Being part of package model already allows each member to access all package model-defined classes, so I was wondering if there is a way to extend this to imports, effectively avoiding to write import same.library in each file if that library is required in the entire package?

Upvotes: 1

Views: 139

Answers (1)

yǝsʞǝla
yǝsʞǝla

Reputation: 16412

I think it's not worth the effort, but "just for the science":

You can use the package object trick:

Define an alias to your imported library whether it's an object, type or function (inspired by scala.Predef):

package object test {
  def pow = scala.math.pow _
}

and then all these package object members are automatically available without import in the same package:

package test

object TestIt {
  val r = pow(2, 3)
}

In a similar fashion you can use another way of doing it through implicits.

Define a transformation/operation that your library does as an implicit:

package object test {
  implicit def strToInt(str: String): Int = str.length
}

Use it implicitly:

package test
object TestIt {
  val strLength: Int = "abc"
}

Implicits don't have to be placed in package object, see implicit resolution for other places where Scala finds implicits.

One more option is to use function scope, or you could an object scope in the same way:

package test

trait Library {
  def doSmth: String = "It works"
}
object Library extends Library

object Scope {
  def libraryScope[T](codeBlock: Library => T): T = {
    codeBlock(Library)
  }
}

And then use it like this:

package test

object SecondTest {
    Scope.libraryScope { lib => lib.doSmth }
}

In all 3 cases you avoid using imports by using them somewhere else once. All these options don't really make your code more clear unless you have some special case.

Upvotes: 4

Related Questions