Scala and Java Interoperability
Last Updated :
30 Jun, 2020
Java is one of the top programming languages and the
JVM (Java Virtual Machine) facility makes it easier to develop in it. But there are small tweaks and features in Java, so developers search for different options like Scala.
Scala and Java interoperability means that a code written in one can be easily executed in another with some changes.
Considering the benefits of Scala like the functional feature (Write less, Work More), built-in data structures, powerful inheritance, and most importantly, JVM support, it has proved to be an effective programming language.
An example of converting Java code into a Scala readable code has been shown below. An example of working with ArrayList is as follows:
Java
// Java program to create and print ArrayList.
import java.util.ArrayList;
import java.util.List;
public class CreateArrayList
{
public static void main(String[] args)
{
List<String> students = new ArrayList<>();
students.add("Raam");
students.add("Shyaam");
students.add("Raju");
students.add("Rajat");
students.add("Shiv");
students.add("Priti");
//Printing an ArrayList.
for (String student : students)
{
System.out.println(student);
}
}
}
Output:
Raam
Shyaam
Raju
Rajat
Shiv
Priti
As soon as the Scala REPL starts, the Java standard libraries are made available. Sometimes it is required to add Java collections in Scala code. The same code can be written in Scala as follows:
Scala
// Scala conversion of the above program.
import java.util.ArrayList;
import scala.collection.JavaConversions._
// Creating object
object geeks
{
// Main method
def main(args: Array[String])
{
val students = new ArrayList[String]
students.add("Raam");
students.add("Shyaam");
students.add("Raju");
students.add("Rajat");
students.add("Shiv");
students.add("Priti");
// Printing the ArrayList
for (student <- students)
{
println(student)
}
}
}
Output:
Raam
Shyaam
Raju
Rajat
Shiv
Priti
However, there are some Scala features and collections that lack Java equivalency. The major difference between the Java and Scala collections is generally put forward as A Scala Traversable is not Java Iterable and vice versa. However, the conversions are possible using some commands. Sometimes, one needs to pass one's collections to the other's code. To make it possible, the following commands are added in Scala code:
scala> import collection.JavaConverters._
import collection.JavaConverters._
The following example shows the conversion of Java collections into Scala and vice versa. The
.asJava and
.asScala are extension functions that enable the aforementioned conversions.
- To convert the Scala collections to Java:
import scala.collection.JavaConverters._
val listInScala = List(10, 20, 30)
JavaLibrary.process(listInScala.asJava)
- To convert the Java collections to Scala:
import scala.collection.JavaConverters._
val JavaCol= JavaLibrary.getList
val ScalaCol= JavaCol.asScala
A Scala Collection can be incorporated using scala.collection and the sub collections can be incorporated using scala.collection.mutable
and scala.collection.immutable
. A Mutable collection can be changed but an immutable collection can not be changed. However, one can still run operations such as addition on the collections but it would only give a new collection and leave the old one unchanged.
An example showing the same is as follows:
Java
// Java Program to return a HashMap.
import java.util.HashMap;
import scala.collection.JavaConverters;
import scala.Predef;
import scala.Tuple2;
import scala.collection.immutable.Map;
public class ConvertToScala
{
public static <A, B> Map<A, B> MapInScala(HashMap<A, B> exampleMap)
{
return JavaConverters.mapAsScalaMapConverter(exampleMap).
asScala().toMap(Predef.<Tuple2<A, B> >conforms());
}
public static HashMap<String, String> Example()
{
HashMap<String, String> exampleMap = new HashMap<String, String>();
exampleMap.put("Ayush", "Boy");
exampleMap.put("Ridhi", "Girl");
exampleMap.put("Soumya", "Girl");
return exampleMap;
}
}
The above code can be converted in Scala as follows:
Scala version of the above program.
scala> val javamap: java.util.HashMap[String, String] = ConvertToScala.Example
javamap: java.util.HashMap[String, String] = {Ridhi=Girl, Soumya=Girl, Ayush=Boy}
scala> val scalamap: Map[String, String] = ConvertToScala.MapInScala(javamap)
scalamap: Map[String, String] = Map(Ridhi -> Girl, Soumya -> Girl, Ayush -> Boy)
In conclusion, Java and Scala Interoperability require some collections of Scala to be assigned to Java code and vice versa. Although, programming in Scala is not tedious and better than in Java considering the fewer number of characters to write the code. Also, the conversions of the two codes make it easier for the developers to get the support of Scala pretty often.
________________________________________________________________________________________
Similar Reads
Java Interoperability - Calling Java from Kotlin Since Kotlin was designed with full interoperability in mind, it allows us to easily use Java classes, methods, and fields from within Kotlin. This seamless integration makes it simple to reuse existing Java codebases while writing modern Kotlin code. In this article, we will understand how Kotlin i
4 min read
Interesting fact about Scala Scala(pronounced as "skah-lah") is general-purpose programming language designed by Martin Odersky. The design of Scala started in 2001 at EPFL, Lausanne, Switzerland. Scala was released publicly in 2004 on Java platform. Scala is designed to be concise and addresses criticisms of Java. Scala source
3 min read
How to go To and From Java Collections in Scala? In their respective languages, Java collections and Scala collections are two distinct sets of data structures that might be frequently utilized. Although Java collections are a factor of the Java Standard Library, Scala collections are made expressly to combine with the useful programming features
2 min read
Program to convert Java set of integers to an Iterable in Scala A java set of integers can be converted to an Iterable in Scala by utilizing toIterable method of Java in Scala. Here, you need to import Scalaâs JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in detai
2 min read
Conversion from a Java Set to a Scala Set A Java Set can be converted to a Scala Set by importing JavaConversions.asScalaSet method. Here, we need to call asScalaSet method which has a java Set as its argument. Therefore, this method returns a Scala Set. Now, lets see some examples. Example:1# Scala // Scala program of converting a Java Set
2 min read