7.6. Using Import Statements Anywhere

Problem

You want to use an import statement anywhere, generally to limit the scope of the import, to make the code more clear, or to organize your code.

Solution

You can place an import statement almost anywhere inside a program. As with Java, you can import members at the top of a class definition, and then use the imported resource later in your code:

package foo

import scala.util.Random

class ImportTests {
  def printRandom {
    val r = new Random
  }
}

You can import members inside a class:

package foo

class ImportTests {
  import scala.util.Random
  def printRandom {
    val r = new Random
  }
}

This limits the scope of the import to the code in the class that comes after the import statement.

You can limit the scope of an import to a method:

def getRandomWaitTimeInMinutes: Int = {
  import com.alvinalexander.pandorasbox._
  val p = new Pandora
  p.release
}

You can even place an import statement inside a block, limiting the scope of the import to only the code that follows the statement, inside that block. In the following example, the field r1 is declared correctly, because it’s within the block and after the import statement, but the declaration for field r2 won’t compile, because the Random class is not in scope at that point:

def printRandom {
  {
    import scala.util.Random
    val r1 = new Random   // this is fine
  }
  val r2 = new Random     // error: not found: type Random
}

Discussion

Import statements are read in the order of the file, so where you place them in a file also limits ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.