Scala and Java Interop
Scala compiles to JVM bytecode, so it can use any Java library directly — no wrappers, no bindings. Decades of Java libraries for databases, HTTP, cryptography, dates, PDFs and more are available from day one. Java can also call Scala code, with a few things to keep in mind.
Using Java classes from Scala
Import Java classes like Scala ones. Everything in java.lang (such as String, Math, System) is imported automatically.
import java.time.LocalDate
import java.time.temporal.ChronoUnit
import java.util.UUID
@main def run(): Unit =
val start = LocalDate.of(2024, 2, 27)
val end = start.plusDays(3)
println(end)
println(end.getDayOfWeek)
println(ChronoUnit.DAYS.between(start, LocalDate.of(2024, 12, 25)))
println(start.isLeapYear)
println(Math.floorDiv(-7, 2))
println(UUID.nameUUIDFromBytes("scala".getBytes).toString.length)2024-03-01
FRIDAY
302
true
-4
36
Java getters such as getDayOfWeek() can be called without parentheses in Scala.
Converting collections
Java collections (java.util.List, Map, …) are different classes from Scala's. Convert between them with scala.jdk.CollectionConverters, which adds asScala and asJava methods.
import scala.jdk.CollectionConverters.*
import java.util.{ArrayList, HashMap}
@main def run(): Unit =
// A Java list, e.g. returned by a Java library
val javaList = ArrayList[String]()
javaList.add("alpha")
javaList.add("beta")
val scalaList = javaList.asScala.toList
println(scalaList.map(_.toUpperCase))
// Pass Scala collections to Java APIs
val jList: java.util.List[Int] = List(3, 1, 2).asJava
println(jList)
println(java.util.Collections.max(List(3, 9, 4).map(Integer.valueOf).asJava))
val jMap = HashMap[String, Integer]()
jMap.put("x", 1)
println(jMap.asScala.toMap)List(ALPHA, BETA)
[3, 1, 2]
9
Map(x -> 1)
| Java type | .asScala gives |
Scala type | .asJava gives |
|---|---|---|---|
java.util.List[A] |
mutable.Buffer[A] |
Seq[A] / List[A] |
java.util.List[A] |
java.util.Set[A] |
mutable.Set[A] |
Set[A] |
java.util.Set[A] |
java.util.Map[K, V] |
mutable.Map[K, V] |
Map[K, V] |
java.util.Map[K, V] |
java.util.Optional[A] |
.toScala → Option[A] (scala.jdk.OptionConverters) |
Option[A] |
.toJava |
Note:
asScalaandasJavacreate lightweight wrappers, not copies. Changes to the Java collection are visible through the wrapper. Call.toListor.toMapwhen you want an independent immutable Scala collection.
null, Optional and exceptions
Java APIs may return null and throw checked exceptions. Scala has no checked exceptions, so the compiler won't remind you — be deliberate:
import scala.util.Try
import scala.jdk.OptionConverters.*
@main def run(): Unit =
val props = java.util.Properties()
props.setProperty("mode", "fast")
println(Option(props.getProperty("mode")))
println(Option(props.getProperty("missing")))
val opt: java.util.Optional[String] = java.util.Optional.of("from Java")
println(opt.toScala)
println(Try(Integer.parseInt("12a")).isFailure)Some(fast)
None
Some(from Java)
true
Functional interfaces and lambdas
Java APIs that take a functional interface (Runnable, Comparator, java.util.function.Function, …) accept Scala lambdas directly (SAM conversion):
import java.util.Comparator
@main def run(): Unit =
val names = java.util.ArrayList(java.util.List.of("Zed", "amy", "Bob"))
names.sort(Comparator.comparing((s: String) => s.toLowerCase))
println(names)
names.forEach(n => print(s"<$n> "))
println()
val r: Runnable = () => println("running a Runnable")
r.run()[amy, Bob, Zed]
<amy> <Bob> <Zed>
running a Runnable
Calling Scala from Java
Java can call Scala code, but some Scala features look different from the Java side:
| Scala feature | How Java sees it |
|---|---|
class / trait |
a class / an interface |
object Foo |
a class Foo$ with a static MODULE$ field; static forwarders on Foo for simple methods |
val x |
a getter method x() |
| default parameters | not available — Java must pass all arguments |
given / using |
ordinary extra parameters that Java must pass explicitly |
| Scala collections | Scala classes — convert with asJava before exposing them |
Useful annotations make Scala APIs friendlier for Java callers:
import scala.annotation.varargs
import scala.beans.BeanProperty
class Customer(@BeanProperty var name: String): // generates getName / setName
@varargs def tag(labels: String*): Unit = () // callable as tag("a", "b") from Java
@throws[java.io.IOException] // declares a checked exception for Java
def save(): Unit = ()Tip: When building a library for both languages, keep the Java-facing API small and simple: plain classes, Java collections, no givens. Use idiomatic Scala everywhere else.
Test yourself
How do you use java.time.LocalDate from Scala?
- Through a special Java bridge library
- Import it like any Scala class
- It is not possible
- Only via reflection
Which import provides asScala and asJava?
scala.collection.JavaConversionsscala.jdk.CollectionConverters.*java.util.Scalascala.interop.*
What is the safest way to handle a Java method that may return null?
- Call methods on the result directly
- Wrap it with
Option(result) - Compare it with
None - Use
Some(result)