Friday, April 14, 2023

Scala vs Java - Differences and Similarities

Scala is new generation JVM language, which is generating popularity as an alternative of arguably 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 have already been done in the 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 its 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 the functional programming aspect, there are many other differences as well. One of the obvious ones is improved readability and succinct code.

Java is always on firing line for being too verbose, I think 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. If you want to learn Scala, you can also checkout this best Scala courses where I have shared best courses to learn Scala in depth. 



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 produces 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 the 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 IntelliJ IDEA  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 its core strength.

The Well-Grounded Java Developer book has some nice introduction on JVM languages like ScalaGroovy, and Closure, which is worth reading.  In this article, we will see such kind of similarities and differences between Scala and Java.

Scala vs Java



Differences between Scala and Java

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

2) Scala is designed to express common programming patterns in an elegant, concise and type-safe way. The 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 a 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.

The 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 deferring 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 an another good buy, contains tons of examples on different features of Scala.

5) Someone can argue that Java is more readable than Scala, because of really nested code in Scala. Since you can define functions inside the function, inside other functions, inside of an object inside of a class. The code can be very nested. Though sometimes 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 any 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 the 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 a 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 reasons to learn Java programming, that Java tools, libraries, and community are it's the 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 in Java, and Scala in its early days, you can be well ahead if you learn Scala now.

On a 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 and Courses on Scala for Java Programmers

Books are best way to learn a new programming language, first of all, they contain complete information but also in much more readable and authentic form. I strongly recommend following, 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, but, if you feel more comfortable with courses then you can take those as well. Udemy, Coursera, and Pluralsight have many free courses to learn Scala, I have listed a couple of them below, you can also take a look. Anyway, here is my list of books and training courses to learn Scala and Apache Spark:

Further Learning
Scala: Getting Started
Learn By Example: Scala
Rock the JVM! Scala and Functional Programming for Beginners

Thanks, folks, Enjoy learning Scala.

12 comments :

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

catia 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

Unknown said...

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

Anonymous said...

Difference between Object Oriented and Functional Programming
Now since Java 8 has some flavors of functional programming, its better Java developer should know key differences between oop and fp.

first and foremost difference is their philosophy. Object Oriented programming focus on classes, encapsulation

Prem said...

why invent a new language if you able to add those missing features in an existing one? looks like Java is bit lazy in supporting those features and scala is sneaking in between.

Chander Shekhar said...

Scala uses java as compiler and generates byte code.then how's it better then java...so it means it just like a framework on top of java. So if you are good java developer than what better then ng does Scala gives?

Post a Comment