scala - import to all package member files (package scope) -
i have multiple class files in 1 package/directory. similar 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
allows each member access package model
-defined classes, wondering if there way extend imports, avoiding write import same.library
in each file if library required in entire package?
i think it's not worth effort, "just science":
you can use package object trick:
define alias imported library whether it's object, type or function (inspired scala.predef
):
package object test { def pow = scala.math.pow _ }
and these package object members automatically available without import in same package:
package test object testit { val r = pow(2, 3) }
in similar fashion can use way of doing through implicits.
define transformation/operation library implicit:
package object test { implicit def strtoint(str: string): int = str.length }
use implicitly:
package test object testit { val strlength: int = "abc" }
implicits don't have placed in package object, see implicit resolution other places scala finds implicits.
one more option use function scope, or object scope in 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 use this:
package test object secondtest { scope.libraryscope { lib => lib.dosmth } }
in 3 cases avoid using imports using them somewhere else once. these options don't make code more clear unless have special case.
Comments
Post a Comment