O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Java Classes from Scala

Using Java classes from Scala is pretty straightforward. If the Java class you’d like to use is part of the standard JDK, then simply use it. You’ll have to import the class if it’s not part of the java.lang package. Let’s use the java.util.Currency class from the JDK:

Intermixing/UseJDKClass.scala
 
import​ java.util.Currency
 
 
val​ currencies = Currency.getAvailableCurrencies
 
println(s​"${currencies.size} currencies are available."​)

No extra steps of compilation are needed. Scala scripts can directly use Java classes. To run this script, type the following:

 
scala UseJDKClass.scala

The output from running the script is

 
220 currencies are available.

If the Java class you’d like to use is not from the JDK but ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required