Chapter 22. Integrating Scala with Java
This book was completed in 2021, so this chapter focuses on the integration of Scala 3 and Java 11, which is Oracle’s current Long-Term-Support release. This is important to mention because there are currently two major Java version releases planned for every year.
In general, the ability to mix Scala and Java code is pretty seamless. In most cases, you can create an sbt project, put your Scala code in src/main/scala, put your Java code in src/main/java, and it just works.
The recipes in this chapter cover issues with converters, traits and interfaces, exceptions, the conversion of numeric types, and more.
In my Scala/Java interactions, the biggest issues I’ve run into deal with the differences between their collections libraries. However, I’ve always been able to work through those problems with Scala’s CollectionConverters
objects. Starting with Scala 2.13, there are now two CollectionConverters
objects:
-
Extension methods for use in Scala code are in
scala.jdk.CollectionConverters
-
Conversion methods for your Java code are in
scala.jdk.javaapi.CollectionConverters
Similarly, conversion methods between Scala’s Option
and Java’s Optional
are handled by these conversion objects:
-
Extension methods for Scala are in
scala.jdk.OptionConverters
-
Conversion methods for Java are in
scala.jdk.javaapi.OptionConverters
These conversion methods are shown in this chapter’s initial recipes.
After the conversion recipes, Recipes ...
Get Scala Cookbook, 2nd Edition 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.