Tuesday, February 5, 2008

Importing all classes but explicitly excluded

Importing is more powerful in Scala than in Java, because it's possible to use import inside functions i.e. you can locally bind the libraries you need. But there's also some syntactic sugar, f.ex. you can import more than one class from one path:
  object Top{
object A
class B
trait C
  import Top.{A, C} // imports A and C from Top package
It's possible to import all in one go with underscore '_'.
  import Top._ // imports A, B, C
What if we have a clash of names, e.g. 'A' is used in two paths.
  object Top2{ object A }
We can import and rename the other one (the new name is alias for the long name in that scope):
  import Top.A
import Top2.{A => OtherA}
What if we need to import all but, say two classes. We could have lots of classes to explicitly type if we do it importing class by class; just using underscore would import also unwanted classes so it is not an option.

We can rename the unwanted to _, which in practice means that the naming is ignored, so effectively it's not imported at all. Let's pretend we have lots of classes in Top1, and we don't need just B and C.
  import Top.{B => _, C => _, _}
The last '_' tells to compiler to import all the others.

1 comment:

Tatiana Moruno said...

good examples, thanks! :)