Scala and Java Interoperability - GeeksforGeeks

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 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 objectobject 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)
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.asScalaA 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 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.Examplejavamap: 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.________________________________________________________________________________________My Personal Notes
arrow_drop_upSave
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 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;    }}
Scala version of the above program.
scala> val javamap: java.util.HashMap[String, String] = ConvertToScala.Examplejavamap: 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.
________________________________________________________________________________________
Akanksha_Rai
Picked
Scala
Scala-Basics
Scala
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala ListBuffer
Inheritance in Scala
Scala | Case Class and Case Object
Scala | Traits
Hello World in Scala
Scala List map() method with example
Scala | Try-Catch Exceptions
How to install Scala on Windows?
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Comments In Scala