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
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Decorators in Python
In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
Random Forest Algorithm in Machine Learning
A Random Forest is a collection of decision trees that work together to make predictions. In this article, we'll explain how the Random Forest algorithm works and how to use it.Understanding Intuition for Random Forest AlgorithmRandom Forest algorithm is a powerful tree learning technique in Machine
7 min read