You are on page 1of 4

SIMILARITIES AND DIFFERENCES BETWEEN SCALA AND JAVA

Similarities:
1. Both are JVM based languages. Scala also produce bytecode. Scalac is Scala
compiler like Javac for Java
2. We can use Java code and Libraries in Scala and Scala code in java
3. Major IDEs like Eclipse, Netbeans, and IntelliJ supports Scala
4. Both are object oriented and Scala goes one step further and supports
functional programming. (Java 8 supports functional programming)
Differences:
1. Scala drastically reduces number of lines from Java application by making
clever use of type inference, treating everything as object, function
passing and several other features

Java
public class Person
{
private String firstName;
private String lastName;
String getFirstName() { return firstName; }
void setFirstName(String firstName) { this.firstName = firstName; }
String getLastName() { return lastName; }
void setLastName(String lastName) { this.lastName = lastName; }
int hashCode() ....
boolean equals(Object o) { .... }
}

Scala
case class Person(firstName:String, lastName:String)

2. Scala supports immutable style of coding, which makes applying


concurrency and parallelism easily
3. Scala has built-in lazy evaluation, which allows to defer time consuming
computation, until absolutely needed and you can do this by using a keyword
called "lazy" as shown in below code
// loading of image is really slow, so only do it if need to show image
lazy val images = getImages() //lazy keyword is used for lazy
computation
if(viewProfile){
showImages(images)
}
else(editProfile){
showImages(images)
showEditor()
}
else{

// Do something without loading images.


}

4. Code can be very nested supports defining function inside function, object
and class
5. Scala supports Operator Overloading
6. Scala treats methods or functions as variables we can pass functions as
arguments and we can return functions as result from functions
7. Scala is Statically-typed
Major Differences:
1. Lambda Expressions (also called anonymous functions in Scala)

Java
list.sort((x,y)-> {
int cmp = x.lastName.compareTo(y.lastName);
return cmp!=0 ? cmp : x.firstName.compareTo(y.firstName)
}

Scala
list.sort((x,y) => {
val cmp = x.lastName.compareTo(y.lastName)
if (cmp!=0) cmp else x.firstName.compareTo(y.lastName)
}

We can see that the code is really similar, but:

Scala
var (maxFirstLen, maxSecondLen) = (0,0)
list.foreach{
x => maxFirstLen = max(maxFirstLen, x.firstName.length)
maxSecondLen = max(maxSecondLen, x.secondName.lenght)
}

In java, it is impossible to modify the content the lambda expression has been
called from.
Thus, lambda expressions in Java are syntactic sugar over anonymous classes
that have access to the final objects of a context only. But in Scala they are
full-on closures that have the full access to the context.
2. Default methods in interfaces (Traits in Scala)
Another feature borrowed by Java from Scala, is the default methods in
interfaces. They correspond to traits in Scala in a way.

Java
interface AsyncInput<T>
{
void onReceive(Acceptor<T> acceptor)
default void read(): Future<T> {
final CompletableFuture<T> promise = new CompletableFuture<>();
onReceive( x -> promise.complete(x) );
return promise;
}
}

Scala
trait AsyncInput[T]
{
def onReceive(acceptor: T=>()): Unit
def read: Future[T] = {
Promise p = Promise[T]()
onReceive(p.complete(_))
p.future
}
}

At first glance, they are the same, but:

Scala
trait LoggedAsyncInput[T]
{
override def onReceive(acceptor: T => ()) =
super.onReceive(x => { println(sreceived:${x})
acceptor(x) })
}

This is not possible in Java


3. Stream Operations on Collections

Java
peoples.stream().filter( x -> x.firstName.equals(Jon)).collect(Collectors.toList())

Scala
peoples.filter(_.firstName == Jon)

In java, we need an additional interface Stream on collections


4. The access to the SQL Databases

Scala
db.persons.filter(_.firstName === Jon).toList

Java
dbStream(em,Person.class).filter(x -> x.firstName.equals(Jon)).toList

5. Scala supports Macros it is a program code conversion during the compile


time
object Log
{
def apply(msg: String): Unit = macro applyImpl
def applyImpl(c: Context)(msg: c.Expr[String]):c.Expr[Unit] =
{
import c.universe._
val tree = q"""if (Log.enabled) {
Log.log(${msg})
}
"""
c.Expr[Unit](tree)
}
}

Log(message) expression will be replaced with


if (Log.enabled) {
Log.log(message)
}

With the help of macros, we can generate the so-called boilerplate code.
In Java boilerplate, we can also shorten the code by using reflections. But
this will impose some restrictions in places that are critical to execution
speed, as reflections are not free.
(Scala-lang.org - Scala for java Programmars, n.d.)

You might also like