Can I import from multiple packages all at once in

2019-01-14 16:05发布

问题:

At the beginning of my Scala files in a particular project, I often have lines like these:

package com.mycompany
package subproject

import common._
import uiutils._
import databinding._
import modeling._

Is there a way to create an object ProjectImports (or package object) that “preimports” all of these imports such that I can then simply write

import ProjectImports._

instead of the whole list, in each of my other project files?

Is this related to the way the scala package is imported in Predef with scala.`package`?

回答1:

You can do it easily if all imports you needed are members of some traits. If you have several traits with functions, inner classes etc. you can create object inherited from all of them. So all their stuff can be imported with simple import MyObject._. Importing class in this way became a bit tricky - you have to create a type member for each class.

For more examples of this technique see Casbah Imports object and Scalaz object in scalaz project.



标签: scala import