Scala import multiple packages

2019-06-20 01:41发布

问题:

I've got some Scala classes and objects, in their own packages. Each package has a package object defining some implicits, so for example import com.foo.bar._ imports all implicits and classes from the bar package

What I'd like to know is, is there a way to define an "umbrella" import, say com.foo.all, such that

import com.foo.all._

is equivalent to

import com.foo.bar._
import com.foo.baz._
import com.foo.qux._
...

I can understand that this might be a little unclear, but if I we consider the case where I have a large number of my own packages, this would clearly be more concise.

回答1:

The shortest form I can come up is:

import com.foo._, bar._, baz._, qux._

For example:

import scala.collection.mutable._, PriorityQueue._, ArrayBuffer._

EDIT

Perhaps, you want to use only some particular things, as @alex23 pointed out, so you may write:

import com.foo.{foo, bar, baz}, bar._, baz._, qux._


回答2:

The Scala way to import multiple classes/objects from the same package is:

import scala.collection.immutable.{Map, HashMap, etc}

Cool Scala only trick: aliasing/renaming

import java.util.{Collection => JavaCollection}


回答3:

Presently you cannot do it trivially, but you can come pretty close with some effort.

If you create a package object all and set type aliases for every class in the other packages, and create forwarding methods for every method (if the others are package objects), then the import will do what you want.

There has been some discussion of an export feature that would make this much, much easier, but it's not even a concrete proposal yet, let alone implemented.

In any case, you don't need to repeat import over and over again:

import com.foo.bar._, com.foo.baz._, ...

but all ways to shorten the list further do not do exactly the same thing (e.g. will import the name bar itself, not just its contents--this may not be a problem for you, but it is something to be aware of).

That said, until the export mechanism comes along, your code will be maximally readable and maintainable if you type everything out on its own line. It's much harder to notice something missing or extra when everything is jammed on one line.



回答4:

If bar._, baz._, qux._ constitute everything in com.foo than you can simply do com.foo._



标签: scala package