7.2. Importing One or More Members
Problem
You want to import one or more members into the scope of your current program.
Solution
This is the syntax for importing one class:
import
java.io.File
You can import multiple classes the Java way:
import
java.io.File
import
java.io.IOException
import
java.io.FileNotFoundException
Or you can import several classes the Scala way:
import
java.io.
{
File
,
IOException
,
FileNotFoundException
}
Use the following syntax to import everything from the java.io
package:
import
java.io._
The _
character in this example
is similar to the *
wildcard
character in Java. If the _
character
feels unusual, it helps to know that it’s used consistently throughout
the Scala language as a wildcard character, and that consistency is very
nice.
Discussion
The concept of importing code into the current scope is similar between Java and Scala, but Scala is more flexible. Scala lets you:
Place import statements anywhere, including the top of a class, within a class or object, within a method, or within a block of code
Import classes, packages, or objects
Hide and rename members when you import them
Syntactically, the two big differences are the curly brace syntax,
known as the import selector clause, and the use of
the _
wildcard character instead of
Java’s *
wildcard. The advantages of
the import selector clause are demonstrated further in Recipes 7.3
and 7.4.
Placing import statements anywhere
In Scala you can place an import statement anywhere. For instance, because Scala makes it easy ...
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.