Wednesday, November 20, 2013

Scala vs Java - Differences and Similarities

Scala is new generation JVM language, which is generating popularity as alternative of arguable one of the most popular language Java. It's not yet as popular as Java, but slowly getting momentum. As more and more Java developers are learning Scala and inspired by Twitter, more and more companies are using Scala, it's future looks very bright. To start with, Scala has several good feature, which differentiate it from Java, but same time it has lot of similarities as well e.g. both Scala and Java are JVM based language, You can code Scala in Java way and Scala can use any Java library, which in my opinion a great decision made by designers of Scala. Since tremendous works has already been done in form of open source framework and library in Java, it's best to reuse them, rather than creating a separate set for Scala. Out of several differences, one of the main difference between Scala and Java is it's ability to take advantage of Functional programming paradigm and multi-core architecture of current  CPU. Since current CPU development trend is towards adding more cores, rather than increasing CPU cycles, it also favors functional programming paradigm. Though this differences may not be significant, once Java 8 will introduce lambdas, but it might be too early to comment. Apart from functional programming aspect, there are many other differences as well. One of the obvious one is improved readability and succinct code. Java is always on firing line for being too verbose, I thing Scala does take care of that and code which took 5 to 6 lines in Java, can be written in just 2 to 3 lines in Scala. Well Grounded Java Developer has some nice introduction on JVM languages like Scala, Groovy and Closure, which is worth reading.  In this article, we will see such kind of similarities and differences between Scala and Java.


Similarities between Scala and Java

Following are some of the major similarities between Scala and Java programming language :

1) Both are JVM based language, Scala produce same byte code as Java and runs on Java Virtual Machine. Similar to Java compiler javac, Scala has a compiler scalac, which compiles Scala code into byte code. At this level, all JVM language like Groovy, JRuby, Scala becomes equals to Java, because they use same memory space, type system and run inside same JVM.

2) You can call Scala from Java and Java from Scala, it offers seems less integration. Moreover, you can reuse existing application code and open source Java libraries in Scala.

3) Major Java programming IDE like Eclipse, Netbeans and InetelliJ supports Scala.

4) One more similarity between Scala and Java is that both are Object Oriented, Scala goes one steps further and also supports functional programming paradigm, which is one of it's core strength.


Differences between Scala and Java

1) First and Major difference you will notice between Scala and Java is succinct and concise code. Scala drastically reduce number of lines from a Java application by making clever use of type inference, treating everything as object, function passing and several other features.

2) Scala is designed to express common programming patterns in elegant, concise and type-safe way. Language itself encourage you to write code in immutable style, which makes applying concurrency and parallelism easily.

3) One difference, which some might not notice is learning curve. Scala has steep learning curve as compared to Java, my opinion may be slightly biased because I am from Java background, but with so much happening with little code, Scala can be really tricky to predict. Syntax of Scala looks confusing and repulsive as compared to Java, but I am sure that is just the starting hurdle. One way to overcome this hurdle is following a good Scala book like  Programming in Scala or Scala in Action, both are excellent books for a Java developer, who wants to learn Scala

4) One of Scala's cool feature is 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.
}

If you love to learn by following examples, then I guess Scala CookBook is a another good buy, contains tons of examples on different features of Scala.

5) Some one can argue that Java is more readable than Scala, because of really nested code in Scala. Since you can define functions inside function, inside another functions, inside of an object inside of a class. Code can be very nested. Though some time it may improve clarity, but if written poorly it can be really tricky to understand.

6) One more difference between Scala and Java is that Scala supports Operator overloading. You can overload nay operator in Java and you can also create new operators for any type, but as you already know, Java doesn't support Operator Overloading.

7) Another major difference between Java and Scala is that functions are objects in Java. Scala treats any method or function as they are variables. When means, you can pass them around like Object. You might have seen code, where one Scala function is accepting another function. In fact this gives the language enormous power.

8) Let's compared some code written in Scala and Java to see How much different it look:


Java:

List<Integer> iList = Arrays.asList(2, 7, 9, 8, 10);
List<Integer> iDoubled = new ArrayList<Integer>();
for(Integer number: iList){
    if(number % 2 == 0){
        iDoubled.add(number  2);
    }
}

Scala:

val iList = List(2, 7, 9, 8, 10);
val iDoubled = iList.filter(_ % 2 == 0).map(_  2)

You can see that Scala version is lot succinct and concise than Java version. You will see more of such samples, once you start learning functional programming concepts and patterns. I am eagerly waiting for Scala Design Patterns: Patterns for Practical Reuse and Design by John Hunt, which is not yet released and only available for pre order. This book is going to release this month.


That's all on this article about similarities and differences between Scala and Java.  Though they are two separate programming language, they have lot in common, which is not a bad thing at all and in my opinion that's the only thing, which will place Scala as Java alternative, if at all it happens in future. As I had mentioned in my post 10 reason to learn Java programming, that Java tools, libraries, and community is it's biggest strength and if Scala can somehow reuse that, it will be well ahead, forget about competing though, it will take years to build such community and code. For a Java programmer, I would say nothing harm in learning Scala, most likely you will learn few good practices, which you can even apply in Java, as corporate sector is still on Java, and Scala in it's early days, you can be well ahead, if you learn Scala now. On closing note, at high  level Scala looks very promising, all design decision made are really good and they came after several years of experience with Java.


Recommended Books on Scala for Java Programmers

Books are best way to learn a new programming language, first of all they contains complete information but also in much more readable and authentic form. I strongly recommend to follow at-least one book, before jumping on blogs and online articles. One reading any Scala Programming book is must to build fundamental, which is indeed necessary, given rather steep learning curve of Scala. Following are my list of some books from which you can choose one.

Programming in Scala: A Comprehensive Step-by-Step Guide, 2nd Edition by Martin Odersky, Lex Spoon and Bill Venners
Scala for the Impatient by Cay S. Horstmann
Scala in Depth by Joshua D. Suereth and Martin Odersky

Thanks folks, Enjoy learning Scala.

9 comments :

Nabeel Memon said...

I think that's injustice. You should've compared Java 8 with Scala since Java 8 developer preview has been out in the wild already. Just to give this post's readers a sneak peek, the code snippet in bullet #8) for java would look like this:

List doubledEvens = Stream
.iterate(1, i -> i + 1)
.limit(10)
.filter(i -> i % 2 == 0)
.map(i -> i * 2)
.collect(Collectors.toList());

Just a one-liner.
If there's one thing that buzzes me off, it's Java's concurrency model. Scala did way better with Akka (Actor model). But even then you can argue using j.u.concurrent package with Java 8's CompletableFuture.

Juan Fernando Fernandez Sanchez said...

Great article. I've translated it to spanish and published in

http://elblogdejufe.blogspot.com.es/2013/11/scala-vs-java-diferencias-y-parecidos.html

Please, tell me if you don't want this translation available

andreaslundblad said...

"Another major difference between Java and Scala is that functions are objects in Java."

Uhm, what? It's kind of true in Java 8, but I would have been less surprised if you said the opposite actually. Is it a typo?

"Scala treats any method or function as they are variables."

Say what?! A variable is something I can store data in. I can't store data in a method or function. perhaps you meant "as they are *values* or objects." (But that would contradict your first sentence.)

"When means, you can pass them around like Object."

Sight.. You don't pass objects around... http://stackoverflow.com/questions/9468069/object-by-reference-vs-reference-by-value

Javin @ Java Array Tutorial said...

@Nabeel Memon,Thanks for your comment. I bit agree with you on that Java 8 will bring more parity with Scala and I could have compared Scala with Java 8, but you do agree with me that almost 80% projects are still in Java 1.6 and lower version. Even Java 1.7 is not fully established in main stream, though I am hoping Java 8 will be gain more ground very quickly as compared to Java 7. It looks well positioned with lambdas, functional interfaces, stream API, new data time API and lot more. By the way, thanks for Java 8 example.

Javin @ Clonning in Java said...

@Juan Fernando Fernandez Sanchez , No worry mate, I am sure Spanish Java developers will enjoy your translation.

Javin @ Java Synchronization tutorial said...

@andreaslundblad, well picked up mate. yes you are correct , I meant Scala there but you are also true on Java 8 context. Since till Java 1.7 we can either pass primitive or object only, passing function to methods will be new and powerful addition in Java 8. It's much like JavaScript, where you pass a function as a parameter to another function. By the way, I did read that stackoverflow entry on "In Java nothing is passed by reference and references are passed by value."

Anonymous said...

Can you spot difference between these two code written in Java and Scala?

Java:
public long add(int a, int b) { return a+b; }

Scala:
def add(a: Int, b: Int): Long = a+b

Both method are accepting two int numbers and adding them, returning result as long, but there is subtle difference between their version in Java and Scala. Java performs integer addition, while Scala performs long addition i.e. it promotes integer to long before adding, to avoid integer overflow. For example if add Integer.MAX_VALUE to Integer.MAX_VALUE result would be different in Scala and Java. Scala will correctly return a positive value, while in Java result of operation will overflow (because it's int addition) and return a negative number. You can argue that who is more correct or Java but I think Scala got it right.

Anonymous said...

in scala returns a negative number too

Technical Worm said...

Please correct 6th point. I think it should be "You can overload any operator in Scala.." . Thanks for the post.

Post a Comment