Open In App

Scala and Java Interoperability

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 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 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.

Article Tags :