Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I import from multiple packages all at once in Scala?

Tags:

import

scala

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`?

like image 475
Jean-Philippe Pellet Avatar asked Apr 21 '11 13:04

Jean-Philippe Pellet


People also ask

How does import work in Scala?

Import in Scala Importing packages in Scala is more flexible than in other languages. We can place import statements anywhere in the code and even hide or rename members of packages when you import them. Note: Users can either import the package as a whole or some of its member methods, classes, etc.

Can you import multiple classes in Java?

the compiler has no way of knowing which Addition class you are referring to. Therefore, if you have two classes with the same name then you can import only one and you will have to use the fully qualified name for the other.

How do I use Scala packages?

Click on file, new then scala project and give it a name. To define a package in Scala you use the keyword package that is then followed by name of the package. To package your code you create a Scala object (. scala) and place it there then store it in your preferred folder in project structure.


1 Answers

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.

like image 163
CheatEx Avatar answered Nov 05 '22 03:11

CheatEx