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 ...
Get Pragmatic Scala 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.