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`
?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With