Packages and Imports

  • Because Scala code is part of the Java ecosystem, it is recommended to follow Java’s reverse-domain-name convention for Scala packages that you release to the public
  • Different kinds of import:
// easy access to Fruit
import bobsdelights.Fruit

// easy access to all members of bobsdelights
import bobsdelights._

// easy access to all members of Fruits
import bobsdelights.Fruits._
          The first of these corresponds to Java’s single type import, the second to Java’s on-demand import. The only difference is that Scala’s on-demand imports are written with a trailing underscore instead of an asterisk
  • imports in Scala can appear anywhere, not just at the beginning of a compilation unit. Also, they can refer to arbitrary values. For instance:
def showFruit(fruit: Fruit) { 
    import fruit._
    println(name +"s are "+ color)
  • Imports in Scala can rename or hide members. This is done with an import selector clause enclosed in braces, which follows the object from which members are imported:
import Fruits.{Apple, Orange} //This imports just members Apple and Orange from object Fruits.
import Fruits.{Apple => McIntosh, Orange} //This imports the two members Apple and Orange from object Fruits. However, the Apple object is renamed to McIntosh. So this object can be accessed with either  Fruits.Apple or McIntosh. A renaming clause is always of the form “<original-name> => <new-name>”.
import Fruits.{Pear => _, _} //This imports all members of Fruits except Pear. A clause of the form “<original-name> => _” excludes <original-name> from the names that are imported.