TExcelTAD
Home › Scala › Scala and Java Interop

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.

scala · try it yourself
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.

scala · try it yourself
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: asScala and asJava create lightweight wrappers, not copies. Changes to the Java collection are visible through the wrapper. Call .toList or .toMap when 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:

scala · try it yourself
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):

scala · try it yourself
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:

scala
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?

  1. Through a special Java bridge library
  2. Import it like any Scala class
  3. It is not possible
  4. Only via reflection

Which import provides asScala and asJava?

  1. scala.collection.JavaConversions
  2. scala.jdk.CollectionConverters.*
  3. java.util.Scala
  4. scala.interop.*

What is the safest way to handle a Java method that may return null?

  1. Call methods on the result directly
  2. Wrap it with Option(result)
  3. Compare it with None
  4. Use Some(result)