Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Tools and Ecosystem

Scala and Java Interoperability

Use Java libraries from Scala and Scala from Java: collection converters, null and Optional handling, lambdas, exceptions, varargs, plus Scala.js, Scala Native and key libraries.

One of Scala's biggest advantages is that it runs on the Java Virtual Machine and compiles to ordinary .class files. Every Java library (logging, JDBC drivers, Spring, Kafka clients, the whole JDK) is available to a Scala program, usually without any glue code. The two languages can even live in the same project and call each other. This lesson explains the places where the two worlds differ, so interop stays smooth.

The code in this lesson is read-only Scala (our runner has no Scala compiler); the runnable examples show the Java and Kotlin side of the same calls.

Using Java classes

Java classes are imported like Scala classes. Wildcards use * in Scala 3 (_ still works):

SCALA
import java.time.{LocalDate, Duration}
import java.util.UUID
import java.nio.file.{Files, Path}

val today = LocalDate.now()
val deadline = today.plusDays(30)
val id = UUID.randomUUID().toString
val text = Files.readString(Path.of("notes.txt"))

Creating objects needs no new in Scala 3 for most classes (creator applications), though new still works: StringBuilder() or new StringBuilder(). Static members of Java classes are accessed like members of a Scala object: Math.max(3, 4), LocalDate.of(2025, 1, 1).

Java's Object maps to Scala's AnyRef, Java primitives (int, double) to Int, Double, and void to Unit. Scala's Int compiles to a JVM primitive wherever possible, so there is no cost.

Crossing the boundary

Collections Convert with CollectionConverters.
Null Wrap Java results with Option(x).
Lambdas Scala functions convert to Java interfaces.
Exceptions All unchecked in Scala. Catch what you want.
1 / 2

Collections

Java and Scala have different collection libraries. Java's are mutable by default and do not have map/filter methods; Scala's are immutable by default. Convert explicitly at the boundary:

SCALA
import scala.jdk.CollectionConverters.*

val javaList: java.util.List[String] = java.util.List.of("a", "b", "c")

val scalaList: List[String] = javaList.asScala.toList     // copy into an immutable List
val upper = javaList.asScala.map(_.toUpperCase)           // a view; wrapped, not copied

val scalaMap = Map("x" -> 1, "y" -> 2)
val javaMap: java.util.Map[String, Integer] =
  scalaMap.view.mapValues(Int.box).toMap.asJava           // Scala Int must be boxed for Java generics

.asScala and .asJava return wrappers around the same data, not copies. If you want an independent immutable snapshot, finish with .toList, .toMap or .toSet. Scala 2.12's JavaConverters is deprecated: use scala.jdk.CollectionConverters (also available in 2.13 and Scala 3). There are matching converters for Optional (scala.jdk.OptionConverters), streams (scala.jdk.StreamConverters) and durations.

Null and Optional

Java methods may return null; Scala expects you to use Option. Wrap results from Java APIs immediately:

SCALA
val home: Option[String] = Option(System.getenv("HOME"))      // None if not set
val maybeUser = Option(session.getAttribute("user"))          // null becomes None

import scala.jdk.OptionConverters.*
val fromJava: java.util.Optional[String] = java.util.Optional.of("x")
val asOption: Option[String] = fromJava.toScala               // Optional -> Option
val back: java.util.Optional[String] = Some("y").toJava       // Option -> Optional

Scala 3 has an opt-in compiler flag -Yexplicit-nulls that makes String | Null a distinct type, so the compiler forces you to deal with Java's nulls. It is worth enabling in new projects. See Option, Either and Try for the idioms.

Lambdas and functional interfaces

Any Java interface with a single abstract method (Runnable, Comparator, Function, Predicate) accepts a Scala lambda directly:

SCALA
val names = java.util.ArrayList(java.util.List.of("bo", "ann", "cy"))
names.sort((a, b) => a.compareTo(b))
names.forEach(n => println(n))

val t = new Thread(() => println("running"))
java.util.concurrent.CompletableFuture.supplyAsync(() => 21 * 2)

Scala's own Function1/Function2 are distinct from java.util.function.Function, but the compiler converts lambdas automatically wherever a Java functional interface is expected. Converting an existing function value requires the interface type explicitly or a small wrapper lambda: list.forEach(n => handle(n)).

Exceptions

Scala has no checked exceptions. You can call methods that declare throws IOException without wrapping them, and the compiler never forces a catch. Use Try to convert exceptions to values:

SCALA
import scala.util.Try
val content: Try[String] = Try(java.nio.file.Files.readString(java.nio.file.Path.of("x.txt")))

When writing Scala code that Java callers will use, add @throws[IOException] so Java code can catch the checked exception it expects.

Varargs and generics

A Java method void log(String fmt, Object... args) is called like log("x {} {}", a, b). To pass an existing sequence as varargs, use the splat * in Scala 3 (written : _* in Scala 2):

SCALA
val parts = Seq("a", "b", "c")
val path = java.nio.file.Path.of("root", parts*)

Java wildcards (List<? extends Number>) become java.util.List[? <: Number], and a raw List<?> becomes java.util.List[?].

Calling Scala from Java

Scala compiles to normal classes, so Java can use them, with a few rules:

  • A case class Person(name: String, age: Int) has accessor methods name() and age() (not getName). Add @BeanProperty for getters/setters that Java frameworks (Jackson, JPA) expect.
  • object Util with def helper() appears as a class Util with static forwarder methods when there is no companion class: Util.helper() works.
  • Default arguments are not visible to Java; Java callers must pass every argument. Use @varargs for a Scala varargs method that Java should call with ....
  • Scala traits compile to interfaces (with default methods when they contain code).
  • Scala Int in a generic position (such as List[Int]) is boxed to Integer.
SCALA
import scala.beans.BeanProperty
import scala.annotation.varargs

class Config(@BeanProperty var host: String, @BeanProperty var port: Int)

object Greeter:
  @varargs def greet(names: String*): String = names.mkString("Hello ", " and ", "!")

Java then calls new Config("localhost", 8080).getHost() and Greeter.greet("a", "b").

For mixed projects, sbt compiles Java and Scala sources together from src/main/java and src/main/scala (sbt and Project Setup), so there is no special setup.

Beyond the JVM

The same Scala code can target other platforms:

  • Scala.js compiles Scala to JavaScript, for browser front ends (with libraries such as Laminar) or Node.js.
  • Scala Native compiles to native machine code through LLVM, with fast start-up and no JVM.
  • Many libraries are cross-built for the JVM, Scala.js and Native from one code base using sbt-crossproject.

Libraries worth knowing

Area Libraries
Web servers and APIs http4s, Pekko HTTP, Play Framework, Tapir (endpoint descriptions), Scalatra
JSON circe, upickle, play-json, jsoniter-scala, zio-json
Databases Doobie, Slick, Quill, ScalikeJDBC, Skunk (PostgreSQL)
Big data Apache Spark (written in Scala), Flink
Streaming fs2, Pekko Streams, Kafka clients
Functional programming cats, cats-effect, ZIO
Testing munit, ScalaTest, ScalaCheck
Utilities os-lib, upickle, scopt, pureconfig, sttp

You can also use any Java framework, for example Spring Boot or Quarkus, though Scala-first libraries usually fit the language better. Spark is the best-known reason many teams learn Scala at all.

The Java side of the calls

Below are two runnable examples that are not Scala. They show what the other end of an interop call looks like: a Java API that returns null and uses Optional, and Kotlin code that treats Java collections and lambdas naturally, much like Scala does.

Java Java: the API a Scala caller would wrap with Option (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Kotlin Kotlin: calling Java collections with lambdas and platform types (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Assuming .asScala copies. It wraps; later changes to the Java collection show up through the wrapper.
  • Forgetting to wrap nullable Java results and getting a NullPointerException far from the source.
  • Using the old JavaConverters or scala.collection.JavaConversions. They are deprecated or removed; use scala.jdk.CollectionConverters.
  • Exposing Scala-specific types (Option, Future, Scala collections) in an API meant for Java callers. Offer Java-friendly overloads.
  • Mixing Scala binary versions between a Scala library and your project.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you safely handle a Java method that might return null?

    Option(x) turns null into None and a real value into Some(value).
  2. 2. What does javaList.asScala do?

    The converters create views. Use .toList, .toVector or .toSet to take an independent snapshot.
  3. 3. Which Java interfaces can you pass a Scala lambda to directly?

    SAM conversion turns a lambda into an instance of a functional interface.
  4. 4. Which annotation helps Java callers use a Scala varargs method?

    @varargs generates an extra method with a Java-style T... signature.

Summary

  • Scala compiles to the same bytecode as Java, so Java libraries just work and both languages can share one project.
  • Convert collections with scala.jdk.CollectionConverters (asScala/asJava) and optionals with OptionConverters.
  • Wrap nullable results with Option(x); consider -Yexplicit-nulls; exceptions are all unchecked.
  • Lambdas convert to Java functional interfaces; use @BeanProperty, @varargs, @throws for Java-friendly APIs.
  • Scala.js and Scala Native extend Scala to browsers and native executables.

Next: Project: Word Frequency Counter