7 minute read

Scala vs. Java: Why Should I Learn Scala?

Matt is a top architect and developer with extensive experience with web, mobile, desktop, and even game development.

There is admittedly some truth to the statement that “Scala is hard”, but the learning curve is well worth the investment. Some of the more complex features of the language (Tuples, Functions, Macros, to name a few) ultimately make it easier for the developer to write better code and increase performance by programming in Scala. Frankly, we are programmers, and if we’re not smart enough to learn a language that has some complexity, then we’re in the wrong business.

Scala is a type-safe JVM language that incorporates both object oriented and functional programming into an extremely concise, logical, and extraordinarily powerful language. Some may be surprised to know that Scala is not quite as new as they thought, having first been introduced in 2003. However, it is particularly within the past few years that Scala has begun to develop a significant following. Which begs the question of “Why Scala?”.

This article examines the advantages of Scala, especially versus Java (since Scala is written to run in the JVM). Scala is not the only attempt to create a “better Java”. Alternatives such as Kotlin and Ceylon have also gone down that path, but they made the fundamental decision to remain very close in syntax to the Java language itself, so as to minimize the learning curve. This may seem like a great idea, but it is ultimately somewhat self-defeating in that it forces you to stay within a number of those very same Java paradigms that were the reason for wanting to create a “better Java” in the first place.

In contrast, Scala was created specifically with the goal of being a better language, shedding those aspects of Java which it considered restrictive, overly tedious, or frustrating for the developer. As a result, there are indeed code distinctions and paradigm shifts that can make early learning of Scala programming a bit more difficult, but the result is a much cleaner and well organized language that is ultimately easier to use and increases productivity.

When comparing Scala vs. Java side by side, Scala’s efficiency is clear.

Scala vs. Java: Which is Really More Complex?

While the simplicity of the Java language has been part of its success, ironically, it has also contributed to its complexity. Sure, you can write nearly anything in Java, but the lines of code required to do so can be daunting. Programming in Scala, on the other hand, has a slightly more complex structure. But if you can write a slightly more complex single line of code that replaces 20 “simpler” lines of Java, which one is really more complex?

The truth is that Java is often just way too verbose. In Scala, the compiler is incredibly smart, so this avoids the developer needing to specify explicitly those things that the compiler can infer. Compare, for example, this simple “Hello World!” program in Java vs. Scala:

Hello World in Java:

public class HelloJava {
    public static void main(String[] args) {
        System.out.println("Hello World!");

Hello World in Scala:

object HelloScala {
    def main(args: Array[String]): Unit = {
        println("Hello World!")

While there’s not a huge distinction between the two languages here, Scala is less verbose even in this simple example.

For a more practical example, let’s take a look at creating a simple list of Strings:


List<String> list = new ArrayList<String>();


val list = List("1", "2", "3")

Certainly there are some tricks in Java to shorten the code a bit, but not in standard usage.

Now consider a case where we have a list of strings that are numbers, but we want to convert that list to a list of integers:


List<Integer> ints = new ArrayList<Integer>();
for (String s : list) {


val ints = => s.toInt)

Thanks to Scala’s functional properties, this conversion becomes extremely simple.

A Class Example: Java vs. Scala

Let’s take things a step further and compare standard bean / plain old Java object (POJO) creation in Java and Scala.

First, the Java version:

public class User {
    private String name;
    private List<Order> orders;
    public User() {
        orders = new ArrayList<Order>();
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public List<Order> getOrders() {
        return orders;
    public void setOrders(List<Order> orders) {
        this.orders = orders;

public class Order {
    private int id;
    private List<Product> products;
    public Order() {
        products = new ArrayList<Product>();
    public int getId() {
        return id;
    public void setId(int id) { = id;
    public List<Product> getProducts() {
        return products;
    public void setProducts(List<Product> products) {
        this.products = products;

public class Product {
    private int id;
    private String category;
    public int getId() {
        return id;
    public void setId(int id) { = id;
    public String getCategory() {
        return category;
    public void setCategory(String category) {
        this.category = category;

Phew. Lotta code.

Now the Scala version:

class User {
    var name: String = _
    var orders: List[Order] = Nil

class Order {
    var id: Int = _
    var products: List[Product] = Nil

class Product {
    var id: Int = _
    var category: String = _

Which language did we say was more complicated?!

Are We Being Fair?

If you’ve made it this far, and are a Java programmer, you may at this point be thinking that I’m making an unfair comparison of code. After all, there’s nothing stopping me from making public variables in Java and then getting rid of the getters and setters.

However, if you think back to the reasoning behind getters and setters in Java, it is specifically for future-proofing. That is, if you later need to add some logic to either the getting or setting of variables you would have to re-write those public variables to use methods instead (which is why the use of getters and setters to begin with is encouraged in Java). However, in Scala programming this isn’t the case. Because of the language design, the abstraction remains intact without needing getters and setters. Consider, for example, this modified User class in Scala that throws a NullPointerException if you try to set the name to null:

class User {
    private var _name: String = _
    var orders: List[Order] = Nil
    def name = _name
    def name_=(name: String) = {
        if (name == null) {
            throw new NullPointerException(" cannot be null!")
        _name = name

And you can still set the name like this: = "John Doe"

Note that this entirely removes the need to pre-configure method accessors.

Moreover, since Scala prefers immutability, I can write this in Scala even more concisely with case classes:

case class User(name: String, orders: List[Order])
case class Order(id: Int, products: List[Product])
case class Product(id: Int, category: String)

Pretty crazy how much less code I have to write.

Taking the Example a bit Further

Now consider a scenario with the above classes where I want to add a nifty little method in the User class that returns a list of all Products that the User has ordered:

In the verbose world of Java:

public List<Product> getProducts() {
    List<Product> products = new ArrayList<Product>();
    for (Order order : orders) {
    return products;

Fortunately, java.util.List has an addAll method, or getProducts() would have been an even longer in Java.

In Scala, on the other hand, all we need is:

def products = orders.flatMap(o => o.products)

You can see just how much smaller the Scala language implementation is. Yes, it may seem more complex to the Scala newbie, but once you actually fully understand the concepts behind it, the Scala code will look far more simplistic than the Java code.

Let’s get even a bit more complicated here. What if we want to only get the Products within a specific Category?

In this case we aren’t able to take advantage of the addAll method in java.util.List, so things get uglier in Java:

public List<Product> getProductsByCategory(String category) {
    List<Product> products = new ArrayList<Product>();
    for (Order order : orders) {
        for (Product product : order.getProducts()) {
            if (category.equals(product.getCategory())) {
    return products;

In Scala, however, the code remains fairly straightforward. We simply use flatMap to combine the products lists from each Order flattened in a single list, then we filter to only include the ones that match the category:

def productsByCategory(category: String) = orders.flatMap(o => o.products).filter(p => p.category == category)

Dynamic vs. static

There has certainly been no shortage of new languages over the past few years, but whereas nearly all the others that have recently emerged are dynamic, Scala is statically-typed.

As a professional developer – though I know and use many dynamic languages – it is my opinion that compile-time checks are incredibly important to write solid code. In a dynamic language, you can never be sure that your code is sufficiently bug-free and robust until you actually run it in a wide range of scenarios. This can lead to potentially serious defects in code that never get realized until the code is in production.


Hopefully, this article stacks up Java vs. Scala enough to give you a preliminary sense of the power and capabilities of Scala and whets your appetite for learning the language. Not only is it a great language that can make programming less tedious and more enjoyable, but it’s also being used by some of the largest companies in the world (LinkedIn, Twitter, FourSquare, The Guardian, to name just a few).

The popularity and usage of Scala is rapidly on the rise, as evidenced by the ever-increasing number of open positions for Scala developers. If you haven’t already done so, now would be a good time to begin riding the wave and stop asking “Why learn Scala?”

Understanding the basics

What is Scala?
Scala is a powerful high-level programming language that incorporates object-oriented and functional programming. It's a type-safe language that relies on the JVM runtime.
What is Scala used for?
A lot of things, ranging from machine learning to web apps. As a high-level general purpose language, Scala boasts an extensive range of possible applications. Scala allows developers to make good use of standard JVM features and Java libraries.
How to learn Scala and where do I begin?
If you are considering diving into Scala, having a background in Java will obviously help and you’ll have no trouble finding learning resources online. However, if you have no Java experience, you will need to learn the basics. Familiarity with functional programming languages will help as well.
What companies use Scala?
According to media reports and official statements, Scala is being used by numerous tech companies, including Netflix, Twitter, LinkedIn, AirBnB, AT&T, eBay, and even Apple. It's also used in finance, by the likes of Bloomberg and UBS.
Why Scala is not (too) popular.
In recent years, Scala lost some of its appeal, which led some to conclude that it’s on the way out. This is a subject of no small debate. While it’s true that some high-profile companies have abandoned it, Scala is still going strong and retains a large following.


Xavier Carpentier
It's not wrong :) But without lambda it's a little bit boring to write it !
Jose Luis Diaz
I agree.
Wael Chaabane
Thx man this is really Helpfull
It looks like Scala has some neat shorthand that creates concise code. But concise code is usually not on the top of everybody's list. What real world problems does Scala solve? If you can talk about that in your next article, that would be great!
This IS unfair, as Java have now the lambdas so many of the constructs can have way less code, similar to Scala's code size.
Xavier Carpentier
Hello Matt, thx for post on Scala ! I like Scala, but about Java vs Scala examples, some functional tricks is possible on Java 8 now...
Also there is a compile error in your infographic. You may need to add a List<Order> argument to the getProducts method.
One of problems that solves is concurrency race conditions. Scala enforce that eveything is immutable and when you have immutable data then you don't care how many parralel operations will read that data. It is easy to write concurrent code.
Igor Kirtak
Ok, so Scala has some features similar to what we use in C#, which make Java look not very good comparing to it, the same as if comparing to C#. I wonder how the article would look if C# was taken as a base...
Nelson Secchi
What happens if Scala is compared against Java with Groovy? Groovy's syntax resembles Scala's. And it is very easy to work in a similar way as shown here. I think the concurrency advantages Scala helps with is more of a restriction than can be conceived in Java/Groovy as well. Either way, I would like to give a try and see for myself the advantages Scala has to offer. Thanks for the article!
Matt Hicks
Definitely there is a lot of functionality here that could be better represented in Java 8, but from my own experience in the enterprise it is a rare case that developers are allowed to use a Java version less than two or three years old. It might be a good next post to compare Scala and Java 8 functionality, but for most Java developers it seems doubtful that they can even take advantage of them at this point.
Matt Hicks
HammerOfTruth, that's a very good point. That would be a great idea for a next article. Josip, though Scala does prefer immutability, it does not require it.
Matt Hicks
I didn't expect so much of a response regarding Java 8. I'll definitely have to do another article specifically comparing Scala with Java 8. However, I will say from my own investigation of Java 8 lambdas that Scala is still a much cleaner syntax and has many capabilities that Java 8 still lacks.
Lambdas will not make Java better than Scala. There are more features like case class, tuples, Options, implicits and monadic future and collections which makes Scala as the great alternative to java. The for comprehension with futures in Scala is the greatest feature that is not mentioned in this article. Java future just sucks. Java 8 is just a copy cat. Type inference by Scala compiler is great to write more concise code. It sounds like a dynamic language with rich type system.
It is not require it, that is true, but all data strucutres are Immutable i.e. Seq, List, Map, val objects, etc. by default. Immutablility out of the box, if you want to use mutable objects you need to specify it. mutable.Seq, mutable.List. It is opposite than Java where everything is mutable and you need do some work i.e. use guava library for immutable collections, use private final variables in constructors to enforce that you class is immutable. You can always write what ever code, no language can stops you in doing that, but when something is Immutable by default that really make things easy.
Jose Luis Diaz
in java 6 using Google AutoValue and Google Guava :)
Thomas Michaud
I'm fairly certain Arrays.asList("1", "2", "3"); is standard usage.
I particularly disagree with this sentence:"Frankly, we are programmers, and if we’re not smart enough to learn a language that has some complexity, then we’re in the wrong business." I already have plenty of things to learn from the tools I already use (new language versions, new libraries, new application servers, etc.). My spare time is always decreasing. In the last decade, fighting complexity for programming languages and libraries has been the main focus for researchers and library implementors. I'm not saying that learning a new language is not useful. I'm just saying that, with such a busy life, energies must be used with care because you risk a signficant waste of time (time is money). Today, I'm not totally convinced that Scala worths the efforts. You say that "Scala has begun to develop a significant following". In August 2014, the TIOBE index ranks Scala at the 39th position with a poor 0.363% rating, well behind Assembly (24th). With such performance, I really don't care learning it. It can be particularly good at something, but, at the end of the day, my bills are paid by Java.
So for Scala, then ;-) No one will change the underlying programming language in an enterprise project just because the new language "is cool".
Matt Hicks
I don't disagree with your statements, but rather I would say they are not in conflict with mine either. My argument is that Scala is a worthwhile primary language and as such is worth the learning curve to replace Java. I readily agree that time is limited as a developer, there's just too many things to learn and not enough time to do so and still get your work done. However, there are things that are worth the time to learn and Scala is one of these things. Spend a little more time investigating it and I find it difficult to imagine you'll disagree. :)
Instead of: object HelloScala { def main(args: Array[String]): Unit = { println("Hello World!") } } Try: object HelloScala extends App { println("Hello World!") } Gets the point across better i think.
Matt Hicks
Though I'm sure it has been fixed at this point, I stopped using that methodology back in 2.7 when it was causing serious performance issues.
Matt Hicks
Though it is a moderately common usage these days I would say that it's still not really "standard". The average Java developer doesn't know of this little gem (ask around to other developers and let me know if I'm wrong).
Matt Hicks
I never argued changing because it's "cool", but because it is far and away a better language. This post barely touches the surface of why I believe this is true, but hopefully it is enough to make you take a deeper look at it. Immediately after I started migrating to Scala from Java I realized that I was able to write the same functionality with only 25% the amount of code on average...that's a big win as far as I'm concerned.
Lê Anh Quân
I'm afraid that the "average" Java developer you know is quite "below" average. That syntax is available since Java 1.5 and it's hard to imagine someone doesn't know it. I was an enthusiast of Scala some time ago (since 2.0 beta) but I have to agree with darkcg that: "at the end of the day, my bills are paid by Java"
Lê Anh Quân
Totally agree. REAL unfair to compare Scala vs Java 1.5 when 1.9 is already knocking at the door. Maybe Matt has been out of Java house for too long to know the change
Matt Hicks
That very well may be the case. :) I definitely understand the mentality, "my bill are paid by Java". Even after I started investigating Scala it was a couple of years before I was really able to do anything at my job related to Scala. Now I'm fortunate enough to run my own software development company and Scala is my language of choice though I still write Java and a dozen other languages when necessary.
Channing Walton
"I can honestly say if someone had shown me the Programming Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy.", James Strachan (
Channing Walton
It has indeed been fixed.
Today, news languages, new tools, new libraries, ... pop up like rabbits, each offers a bit of improvement over the others. Somebody have a lot of free time to play around. Gone are good old days of naked C ...
Nelson Secchi
Thanks for the quote Channing. It is good to know that Groovy's creator acknowledges that. But I am tempted to ask, what is the future of Groovy then? Will Scala take over? I am thinking that great RAD frameworks such as Grails which rely heavily on Groovy. @disqus_4gBCa3DMWa:disqus a question that I see no one has asked, how much effort is required to migrate from Java to Scala? (In general, of course)
Matt Hicks
It is a commitment. It took me roughly six months of playing around with it part-time while still working in Java full-time before I felt comfortable with Scala. However, after the first few hours using Scala I realized the potential of the language and how much time and effort writing Scala code instead of Java would save me. I would definitely recommend "Programming in Scala" as a great way to get started. I've read it twice myself.
Matt Hicks
This is truly ridiculous. Java devs comparing Java 8 and Scala is like the Java developers praising the crumbs falling from the table while the Scala developers are eating a feast...lambdas are a big improvement, but they are by no means even a fraction of what Scala is capable of.
Channing Walton
I would add that learning the scala syntax and programming with similar idioms to Java is pretty quick - weeks. Learning the new eco-system of libs is months. Plumbing the depths of the type system is years ;)
Lê Anh Quân
It's really funny you said that. FP support in Java is what Java devs had long wished for and it's why I was interested in Scala or Groovy in the first place. I know that Scala has many more to offer, but it's FP that truly sealed the deal. It's good that you are enjoying your feast there, but > 90% of your post is about FP support in Scala, and if you let it be "scrumbs" to fall out of table, then I'm afraid your feast has very little thing left to enjoy. :P Peace PS: I don't think your POJO argument is a valid one, last time I checked, POJO class that Scala generated contains tons more things and is no longer "Plain Old", and I don't think it will be compatible with Java POJO
Lê Anh Quân
For those who curious about Scala vs Java 8, here is a valuable post at StackOverFlow: After all, Scala is a new language, not a Java extension, so take a great care before making the switch. For me, I would bet my free time into javascript frameworks like AngularJS or Ember... The client is thicker everyday and server side is so much thinner to the point that code optimizing is no longer necessary
Sebastián Tramontana
I agree!
Sebastián Tramontana
Great article! SCALA reminds me of C#, with their lambdas expressions and properties accesors.
I agree. By code "optimizing" I assume you mean reducing code size not increasing performance. I say that because most tests agree that Java, in general, performs better than Scala.
samuel heaney
Even using Scala as Java provides less boiler plate code. As well as everything @Josip mentioned, you have one of the more advanced type systems that far outweighs the Java type system which helps you catch more errors at compile time. I think it's frankly unfair to compare Scala with Java. Maybe Scala and Go would be a more fair comparison.
so you value a new technique by its popularity? you should really not learn scalar then.
If you try to learn every language some bearded guy wearing pair of sandals in a tie dye shirt tells you about, you won't be in ANY business at all!
The point is that you don't need to preemptively add JavaBean-style boilerplate code like <code>getFoo</code> and <code>setFoo</code> methods when you don't yet have any need for custom logic in them, only as a defensive measure so that you don't break callers if you do need to add logic to them in the future. By declaring a public property on a Scala class, the compiler is effectively generating a getter (and setter if it's a <code>var</code>) for you anyway—it is not direct field access: methods that take no arguments can be called without parentheses in Scala, and there is special support for <code>def fieldname_=</code> to allow assignment syntax. So the key point the author is making is that you can later add logic to that property access <em>as a refactoring that's completely internal to the class, no name change that breaks callers</em>. In short, idiomatic Scala adheres to the Uniform Access Principle; Java does not.
One chance to start winning people over though might be test suites... that's a sometimes-cited means of slipping in some Scala to let people see benefits and become familiar without riling up management much, since it's not production code. After all, Scala 2.11 is just a jar that will work in your Java 6 projects... at least until 2.12 that will require Java 8 :-)
Ko-Chih Wu
To put it in the perspective, the current Groovy project lead responded to this quote: > It's funny how those famous words from the original founder James Strachan resonate. James was involved in the first two years essentially, and then worked on other projects. > Imagine that something like JPA in its current state had existed 10 years ago: do you think the Hibernate guys would have created Hibernate? Most probably not. But it doesn't make Hibernate less valuable, not worth investigating, or deemed to be going away.
I wouldn't. These JS frameworks are evolutionary steps. As new standards like Web Components, EcmaScript 6, etc. continue to evolve, the frameworks are likely still going to change significantly <a href="">or be surpassed by whole new approaches</a> other than today's data binding. Angular 2.0 already has major API changes from prior versions. And let's not forget that programming in plain JavaScript sucks :-) Languages trans-piling to efficient JavaScript "assembly" is rapidly becoming realistic. If the afore-linked article on React and Om is intriguing but you're far less likely to get into Clojure than Scala, take note that <a href="">Scala.js</a> has progressed quickly, Scala(.js) should be able to exploit the same symbiotic advantages of immutable collections in tandem with React that ClojureScript/Om does, and that <a href="">Scala.js integration with React is well underway</a>. As for the "server side is so much thinner"—that's the middle tier, not the entire server-side. I don't imagine Apache Spark will run atop HTML5 local storage anytime soon :-) Get a taste of <a href="">Akka</a>—which you can also use in Java BTW—and think about the types of things that can be productively built with it (like, say, Spark), and it might seem there's still a lot of fun to be had on the backend.
I was trying to be helpful, to you if you genuinely didn't understand, or to other readers. You're welcome :-P
Lê Anh Quân
Well, that's a whole lot of NAMES you put into the reply. I'm truly impressed. I don't have as much knowledge as you. Frankly I'm confused here. My argument was that I have little time to spend on studying everything. So I have to choose which one to study next. And I choose not to study Scala because it has little value over my old Java, and instead I will study AngularJS, which will vastly upgrade my client scripting ( JQuery and JS ). Are you saying that I'm wrong? What would you suggest me to do next?
No, certainly there is nothing wrong with developing new client-side skills if you're seeing projects and opportunities that interest you, and it might be a refreshing change if you've worked in Java a lot. I was just hoping to point out a few areas where I feel Scala <em>does</em> have potentially compelling value—I probably got carried away :-) I think I'm biased, because I've been working with dynamic languages lately, and it feels like a lot of dust is stirred up on front-end tech right now. So statically-typed backend is actually appealing to me personally as an area to focus while it settles a bit ;-) Consider giving React at least a shallow look after you become familiar with Angular, though. And a functional language if you can ever find the time. Not as mainstream, but they'll definitely give you some new ways of looking at problems even in your day-to-day environment.
Lê Anh Quân
Thanks for the suggestion ches, I appreciate it. It's ok that many people are assuming Java guys are "non-functioal" guys. I had looked at Ruby and Scala since 2008, and even I cannot match them with my job, I've been a big fan of functional style since then. And Java never stopped me. I said it so you know that if Scala was a big offering to me then I have switched to it long time ago already. Now I've been a full time free-lance for some time, it's even more important to pick the right tech stack to do the job. I paid a big price with the NoSQL band wagon earlier (few years of reduced performance and less stable products) so now I'm even more skeptical with tech choices. Most of the time I'm the only technical guy that customer can rely on. The feeling when I hurt their business because of my pure childish technical interest is unbearable. Need to be more responsible now. So yes Scala is a shiny new toy, and I would love to work with it if some customers specifically request me to, but I would not suggest it. My old ruggy Java (and trusty SQL dbs) still do the job just fine.
Lê Anh Quân
Agree. But I don't think AngularJS is "a bit of improvement". I've been working with it for few months now and found myself extremely happy with it. Nothing come close. Really admire the guys behind it
Huge Web
I would love to work with Haskell after all that Ruby, Scala and Java gaining traction in the markets. Haskell still stand out being the reliable functional language. I still can't understand why won't most commercial start adopting Haskell before switching to Java 8?
Huge Web
In Asia like Singapore, Java is widely used and Scala is non-existent after I have completed my Scala course at Coursera for a year. I'm considering Haskell as an alternative to Java. Groovy are almost non-existent in Asia as well.
Caleb Barr
Scala's syntax can get even more concise than shown above. For example: def productsByCategory(category: String) = orders flatMap { _.products } filter { _.category == category }
If we were afraid of metals we wouldnt use the trains...
Lambda Pool
well... if you implement interfaces you can really do some near from that but its not the same. Still more bureaucratic than Scala version by some miles. its just closures, Scala has currying, high order functions, you can overload operators... java 8 has some closures so what's the big deal?
Lambda Pool
there is no such thing of "logic inside getters" if you do that you are violating some best practices in Java. Scala prefers immutability for safer code.
Lambda Pool
Scala was created in 2003, its not a new language at all. You guys are outdated, not the languages.
Lambda Pool
its doesn't necessarily true, you can invoke a java class from Scala and vice versa.
Hello Matt, I like to learn scala . I dont know any other programming language . its is a right choice to go with SCALA first . or i need to learn any other language first
Otto Wagner
Nice Tutorial. So, traditionally. I always though the point of getters and setters were to dictate read and write permissions to members of a class and its members. Does Scala, in your opinion, make similar access control more complicated?
D'Glester Hardunkichud
Straw man (stupid) argument.
Jose Luis Diaz
Why did you choose this sintaxis: class User { var name: String = _ var orders: List[Order] = Nil } and not this one: class User (var name: String, var orders: List[Order])
Joshua Partogi
So the reason to learn Scala and use it over Java is syntax reduction? There are other languages that is better than Scala. The syntax in Scala and the number of keywords is so daunting for beginners.
Julian S
I think this article just convinced me to learn some scala.
bloody fool
Java Rocks.... Lets Scala run on its on VM then will think of an alternative. Java has lots more scope than any other language out there today. Java has lot of potential for improvement, and i'm sure one day all these giggles will stop and people start using Java more often than ever.
Its clear that you know nothing about oop, but you certainly love pretending you do.
.. or just use a struct in C or C++ and don't bother with empty, useless accessors on value objects in the first place..
Exactly. The world doesn't need yet another method to dig a ditch. No value here.
My, these kinds of posts sure do bring out the get-off-my-lawn haters. A Real Man should never need anything more than x86 assembly, right? Really though, if you're not too big on associating behavior with data in the way OOP has come to be imagined, you'd like algebraic data types, which Scala's case classes can serve as.
Its clear that you nothing about oop. Gain some experience first.
Shouldn't have fed the troll. Live long and prosper, my bitter, bridge-dwelling friend.
what about working with xml in scala? :D
Phaser Editor 2D
Hi, good article, thanks. Maybe you can update it with the new features of java8, like lambda, the function package and the new collection methods. With them, the distance between java and scala was reduce a lot. But you know, yet I prefer Java in the old foreach/addAll fashion, it makes me easy to debug and find bugs. The same with getter and setters. I am Java and python developer, and I prefer the verbosity of Java in complex systems.
Ali Ghahramani
Hello & thank you for the article. Just two alternatives : 1. case class User(name: String, orders: List[Order]) can be written as : class User(val name: String, val orders: List[Order]) 2. val ints = => s.toInt) can be written as : val ints = - I think it is important to learn Scala because of on going projects such as : Spark and Kafka
The most important question is... Why the Java developer has a old screen and the Scala developer has a nice laptop? :D Good article!
Interesting discussion... and it repeats itself over and over again... C++ and Smalltalk... What I like about Scala is its terseness / conciseness - and static typing. Any help from where ever it comes to start with less (undetected typo) bugs, the better. --- There are multiple Ends of the day. Certainly paid bills is one end. Another is: No language will help to understand a problem and find a solution, but if I can find a language with much less noise than C-'inspired' ones, I like that. When taking in code, reviewing code, validating code, etc. having to scroll is already noise. There is a healthy middle ground between verbose language and the other extreme, such as APL, and Scala feels that way.
Apparently at that time (when he wrote the post) he never learned that this is possible in Java: Stream<Products> p = -> o.getProducts().stream()) or... instead of getProductsByCategory method: o -> o.getProducts().stream() ).filter( p -> p.getCategory().equals(category) ) or... Arrays.asList("a", "b", "c"); Regarding to getters and setters, Scala is cool. Java has an third party library to reduce the boilerplate code of getters and setters too (and other things).
Edward Beckett
Java 8 > List<String> list = stream.collect(Collectors.toList());
"Frankly, we are programmers, and if we’re not smart enough to learn a language that has some complexity, then we’re in the wrong business." Here are a couple of thoughts you may like to consider before throwing out the above value judgment: - Almost anybody is smart enough to learn a new language like Scala. It might just take some a little longer than others. - You get into the business that you like the best. - "tal" is nowhere near a success-indicator as desire, satisfaction, and inspiration. - If one doesn't find enough ROI in a particular technology, learning it is their prerogative. - elitism is not a virtue. - Scala is pretty sweet. Please don't discourage others from tasting it.
Marius Kotsbak
Hmm, just use val for read only properties, and var for mutable properties.
Marius Kotsbak
Do both. Study Scala.Js and the Angular or React wrappers.
Harmeet Singh
With the help of Java8 now our Java code is more precise. And i am just follow the term that every language have its own benefits, according to our requirements, select language, because its time for polymorphic programming.
Neither do they know Scala, so that isn't a distinction
Nawaz Ijaz
Hi Matt Hicks, Java8 has my vote but i am still interested to learn the basics of Scala and Groovy. How do you rate Groovy and compare it with Scala in terms of capturing the future market. As of today, Scala stands at 30th position and Groovy at 39th position
I once looked at Lambda Calculus and kind of loved it. Since then I developed the desire to learn a language that was somewhat Functional. And that was my sole motivation. Scala has both Functional and Imperative traits. I must say that I am loving learning Scala. At no time have i ever felt it would replace Java.
Richard Eng
I do not agree with the notion that a complex language is worthwhile because you can be more expressive and productive once you climb the steep learning curve. Complex languages impose a severe cognitive load on the developer, even if he's not aware of it! Moreover, languages such as C++ and Scala are much harder to master. Why is this significant? Because when you've mastered a language, you can work at your maximum effectiveness and efficiency. That's why I favour syntactically simple languages, such as Python, Go, and in particular, Smalltalk. You can be very productive in these languages, as well (in fact, that's the primary strength of Smalltalk). This illuminating post supports my view: Also, while Scala code *can* be very concise, it can also be wickedly difficult to read. I've heard this from many developers. I greatly favour readability in a programming language, even if it's not as concise as Scala, even if it means additional LOC. The aforementioned languages are good examples. The above is true, despite the highly condescending statement: "Frankly, we are programmers, and if we’re not smart enough to learn a language that has some complexity, then we’re in the wrong business." Let's not make programming an elite activity. (And take pity on me, a mentally-deficient C/C++ programmer with over 20 years experience.)
Stefan Malic
Hi everyone, I have a very newbie question, so please be kind: what is Scala for? Desktop or mobile apps or what?
So, null pointer exceptions are possible in scala? Sorry, I see this language was only written to implement as much fancy things as possible, without actually thinking abut design.
Daniel Dietrich
Hi, I've stumbled upon your article. In my opinion tuples and functions are the most simple building blocks of Scala, contrary to what you said. Please take a look at my functional component library Javaslang ( Of cause it cannot compete with Scala because of the lack of pattern matching, for comprehensions, a more sophisticated type system etc. But you may find it useful because it contains abstractions of Tuples, Functions and also a full-blown functional collection library! Cheers Daniel
Soooo instead of learning something more useful like C# which is widely used, supported and implemented, there's a hipster language(Scala) that does some stuff better than Java. I would highly recommend people get better at languages such as JavaScript before trying to learn something that no one would ever use in production.
Chitresh Deshpande
Nice post. Can you point me to some good resources comparing other facets of Java - multi-threading, garbage collection, NIOs etc with Scala?
Li, Yao
A nice post with detailed and insightful code comparisons! However, I'm afraid the code comparisons between Scala and Java tell only half of the story. People might think:"Well. It's just some sugar syntax." Then they are probably gonna miss the type inference feature which helps you find many more bugs in your program even before running it, the interactive experiences brought by Scala REPL, the macros and the upcoming scala.meta which make meta programming much easier, and so on. And do not forget that there are still a bunch of mad scientists out there constantly bringing crazy new ideas to it.
Theres a whole of issues with Scala's design principles/philosophy: 1) in teh first example when defining classes, Scala completely leaves out scope & accessibility of the class and its features and lets teh compiler "assume" or ignore during compile time and be decided on during run-time. That's a horrible language flaw. Scope, accessibility, must be explicitly stated, its an application logic and programmer decision. 2) in the lists example - again type declaration must be explicit otherwise during runtime. In a large process say the programmer mistakenly throws wrong objects into the list and later gets unexpected results bc of it? wouldn't it be hard to trace? 3) scala does not need an explicit visible end statement delimiter. Consider these two snippets of code: class User { var name: String = _ var orders: List[Order] = Nil } VS: class User { var name: String = _var orders: List[Order] = Nil } How does Scala know in the second example "var name: String = _" is separate statement from "orders: List[Order] = Nil"? I get that Scala is more intellectual in the sense that it even incorporates standard OO practices into the language...but as a Java developer who strongly follows structure and explicitly stating things, i would still pick JAVA any day. And not to mention, Scala is definitely not a beginner's language, its for people that have good experience with OO programming.
MY POINT EXACTLY! i too noticed that design flaw. how does scala separate statements? My assumption is by keywords/terms but then again that would a huge resource hog...
definitely learn JAVA first as Scala is the next evolution(in certain ways) to JAVA. is an excellent resource for learning Scala and Play Framework. Learn more at
Robert Jackson
I hate tricks. My fucking time is too important to learn tricks about BS. I want a way to program, not thinking about xyz. This is why I am now starting to hate programming.
Robert Jackson
I met a retired engineer who almost went into Comp Sci, he told me there were too many unknown variables to waste his time learning to program or programming. He built a fucking awesome 60 foot by 16 by 2 story pontoon Yacht
Robert Jackson
yes lets waste all of our time learning the ins and outs of just, just one language.
Robert Jackson
You mentioning "in java 6 using" shows how flawed programming is these days.
Robert Jackson
a gem is a hack, a hack is bullshit.
Jose Luis Diaz
Then stop using String, because is an extension of Java been written in java. Not sure if i understand your point. A library is a library, no matter if is a builtin or not.
Artiom Lukianov
Why not Kotlin?
Niceeee post.........Thumbs upp
Nicee post... Helped us a lot... Thumbss up
Thom Snyder
Scala is 14th on Redmonk January 2016 ratings, accelerating. Full disclosure: I am a Lightbender.
Lets waste all of our time learning the most popular programming language of the world?? I don't understand. Remenber, the java code is present everywhere.
def products = orders.flatMap(_.products)
Buri Nazar Wale Tera muh Scala #BeingSarcastic ! BTW good comparison of scala and java :-) , I am scala programmer and I would definitely replace Java with Scala wherever it is possible :-P
"Frankly, we are programmers, and if we’re not smart enough to learn a language that has some complexity, then we’re in the wrong business." good ole arrogant programmers
Blonde Viking
"less commonly known" = "hack"??
Mac Krzysik
Great article. It took me a few Google queries to get an understanding of the related concepts like case classes, but all for the better. Thanks
Amitabh S
Java 8 may be functional, but its still JAVA! So we cannot get rid of public static void main and Foo foo = new Foo(...); etc.
Amitabh S
Ahh a typesafer.
Sergey Klenachev
It's a nice article, Matt! You're right about Scala. It's not so difficult to learn it and it has more easier and faster way to make code and to develop big and complex apps. I think Scala code is more clear and readable. I've been a Java developer at Redwerk company when we started using Scala. I like to develop complex and useful solutions at our company using Scala At each project with Scala at Redwerk, I feel that I've made the right choice to learn this nice powerful programming language!
In Minnesota's state government, we used COBOL and that was good enough. Sincerely, Walter Mondale
IL Mare
Java: List<String> list = new ArrayList<String>(){{add("1"); add("2"); add("3");}}; List<String> list = new ArrayList<String>(); Collections.addAll(list,"1","2","3"); List<String> list = Arrays.asList("1","2","3");
"lots", "lot", "i'm sure one day" - very informative, reminds me "make America great again"
Robert Jackson
FFFS wake the fuck up child. The most popular programming language changes weekly. I know you have not been programming long by your comment.
I have started working with Scala and Java 2 years. And i found Scala makes you more compiler dependent. Do some sort of complex pre-processing before generating the byte-code. Apart from this it has few more benefits over java. But JDK-8 came up with Lambda expression and Functional interfaces, which makes decision of switching to Scala more complex. More often switching a language or platform require strong performance related arguments. The number of lines of code for execution is no lesser in scala compare to java. Almost all the languages in this world have some sort of weaknesses. As tackling real life complexities in current world not only require a highly scalable language but also the equal developers and organisational efforts to match those scalablity. Using a language for a special purpose is different than using one for general purpose. Developers must realize the major differences.
Robert Zaremba
I don't see much advantages in Scala any more. Nowadays Java has lambdas as well, functional libraries (you can do map, flatMap etc...) and the code is as expressive as Scala one, compiles way faster, is less magic and more straightforward. Scala has many traps with it's "reach" syntax, which is very dangerous at the end. One can finish with constructs like: ``` scala> (3.some |@| 5.some) {_ + _} res18: Option[Int] = Some(8) scala> val f = ({(_: Int) * 2} |@| {(_: Int) + 10}) {_ + _} f: Int => Int = <function1> ``` or have a type error like this one: ``` error: type mismatch; found : scala.util.Try[Main.Result[_ >: Some[String] with Option[T] <: Option[Any]]] required: scala.util.Try[Main.Result[Option[T]]] ``` Did you try Kotlin? It comes as a remedy for Scala problems.
Point made regarding Scala being terse :) However, while I love the last example with `productsByCategory()`, I cannot stop wondering about the unneeded extra processing Scala methods seem to do. I mean, in Java, we simply go through all products of all orders (without creating new structures) and simply get the ones that match out criterion (category here). In Scala it looks like we are going through all that to first create a flat map and then we iterate it to finally obtain what we're after... I know that creating objects is not expensive (anymore) for the JVM but still... it looks to me like unneeded extra processing that at one point might add up...
Pablo Iribarren
The most popular (mean used) programming language is javascript.
Will you please rewrite the artical keeping Java8 in mind. It is very easy to say Scala reduces the number of lines in a given code base, however at what cost. I found Scala leads to maintanence hell. Anyway this is my side of the story.
As a developer; most of my time is spent in designing systems, integrations and algorithmes. It really does not important what language you use if you are targeting backend systems. Writing fewer lines does not change my life.cYou need to hand over your code. It is hard to find developers with knowledge of scala, ceylon, etc. Yes they are not hard to learn; but people does not willing to learn unfortunetly.
Devendra Bhatte
So, said the COBOL programmer too ;-)
How about performance difference? If Java and Scala compile down to Byte-code and JVM, the performance should be the same right? So you get to learn some expressive coding in Scala without any performance gain.
Olivier M.
"Phew. Lotta code" .... Seriously ? We have IDEs today that can generate most of it in just one click.
I don't think having someone or something writing/generating the source code is the problem... I think the problem lies in ending up with lots of (code) noise in our source files, files that we need to re-read/review over and over again. We end up doubling, tripling our classes with trivial code destined to support well-established conventions, specific to the very technology we're using. Since we all agree on those conventions, why not have the compiler generate that for us, in order to minimize friction to our eyes and brains. One can argue that we could simply ignore that piece of code but, IMHO, the more code we have (not to mention the added complexity of the problem we're trying to solve), the easier it is to loose track of important aspects and the greater the effort we need to make is in order to understand what we're reading...
Dileep Kunaparaju
At present JavaScript but may vary on time !
Nikola Bunic
I have to add something about reducing Java code (e.g. setters/getters.) especially for lazy programmers like many of us :) There is project Lombok ( where code can be reduced by adding annotations.
lol what
Again, please read this ;)
Don Vaillancourt
The Hello World example for Scala can even be simpler than what's provided in this article. But otherwise, ever since I've learned Scala, I'm forced to wonder why people still use Java. Developing in Scala is so fluid and intuitive.
abhineet kapil
@disqus_4gBCa3DMWa:disqus Hi Matt, Does the conciseness advantage of Scala still hold true "significantly" after Lambda's were introduced in Java8.
There are so many languages. Are you willing to learn them all? It is not about smart. It is another waste of time. It is really funny to say some language is better just because you can type less.
Matt Hicks
David, I know dozens of languages and have read the basics about many more. However, I don't disagree that trying to learn them all is a waste of time, but I don't see how that's applicable to this discussion. Scala is one of the most powerful languages in existence today and worth the effort to learn. For a professional developer that makes his living of his efficiency in code, typing less is a pretty big factor. Are you suggesting that all languages are equal and that learning any new language is a waste of time?
maybe I am wrong. My thought is if it is still based on JVM. It is not really new. It may be a hot topic. But I suspect how long it will last.
Matt Hicks
Well, you're a little behind. I wrote this article a couple of years ago and Scala has grown by leaps and bounds since then. The larger companies in the world are heavily using it. Twitter, FourSquare, Wix, almost exclusively use Scala while Netflix, Amazon, Google, and many other large companies leverage it in more advanced use-cases. There are things that Scala can do that no other JVM language can do. For example, Scala Macros create a powerful alternative to Java's Reflection to allow you interact with the compiler to generate functionality that is simply not possible until runtime in Java. Scala.js and Scala Native allow compilation of idiomatic Scala out of the JVM and into JavaScript or into native code. Scala is a far different creature than nearly anything else in the JVM ecosystem and you'd be wise to dig a little deeper before casting it aside.
cool story bro
Hello, World in Scala is: object HelloWorld extends App { println("Hello, World") }
Mahbub Zaman
How are these .flatMap, .fitler stuff not just additional library support? Why call it another language?
Imran Yusubov
Nice article, but it is only focused on shorter code. To me, it does not matter whether 20 lines or 1 line does the same thing as long as it does the work and does it correctly. I think Scala shines in functional programming and concurrency, where Java has put a lot of effort in Java 8, but Scala was designed from the ground with that in mind. I really would like to see what makes Scala better on concurrency.
Sujoy Datta
is that all advantage for scala development??? do you mean if in java implement a logic if it takes 1 day, in scala it will take half a day , is that the only thing ???
You are talking about a RELP, that is different. That is not a language feature, It is a tool. You can install a RELP for Java if you want. Also Java 9 has its own RELP now. RELP:–eval–print_loop Java 9 RELP:
Kamlesh Kumar Singh
java 9 have also these type of syntax: for List you can use .. List list = List.of("1","2","3");
Ramdhan Nurrachman
Create compiler inside compiler? I dont mind if java was created from C but make another compiler based on java/JVM? Waste of time dude
Ramdhan Nurrachman
Matt Hicks
Scala can now compile to JVM, JavaScript, and native.
Akshay Sachdeva
Its amazing to me how fast articles get stale in todays world. As scala has matured and the mathematics of mathematics in category theory is now amenable in such amazing libraries from the scala community, you realize, that the object oriented programming and domain models we constrained ourselves in were only meant to break down the problems so we can understand them and maintain them, but its limiting. akka + cats + circe + shapeless + pureconfig + gatling + (scalaz) [I do realize that the above 2 lines will also be stale soon.] A critical grok of any of those repos and you realize java simply cannot compete in the new function as a service space and the sheer brilliance in that language and the scala compiler. Ones ability to re morph and refactor code in scala is unparalleled for production code. I think your article missed on no mention of the amazing test discipline, libraries, and patterns that scala brings to the keystrokes. Test code is App code. I do love the message in the article and thats the good stuff. Thanks
crush with logic
Good god. Has the author of this article even programmed in Java for more than an intro to programming 101 course? The absolute ignorance of what Java has to offer makes the author come off as exceptionally biased. Unreal. Even as far back as Java 6, much of this functional programming was possible in Java with a few common libraries.
Fareed Al-Namrouti
why would i need a JVM in the first place when we are all using Linux Servers ?! from my opinion both are Shit! people should just give up trying to fix JVM and live in the future with us.
Moayad Abu Jaber
by any chance did you do that? because I really want to know the features exist in scala and not exist in java 8!
Matt Hicks
There are many articles on this topic: I don't really think I have a lot to contribute to the conversation apart from saying that even though Java 8 and Java 9 improve the language toward supporting some aspects of Scala, Java can never be as expressive simply because of the backward-compatibility requirements on it. Java is a good ecosystem of simplicity, but Scala is a more modern and advanced language offering much more than Java ever can.
Hello world gets even shorter in Scala. `object MyFirstProgram extends App { println("Hello World") }`
It just sounds like your arguing with writing less code. Sure you write less code by at the cost of context def products = orders.flatMap(o => o.products) this makes no sense to me. The Java example I can read what the code is doing, it's self documenting. As for writing less code we have generators these days that create boiler plate code. No need to hand write getters and setters and even all the scaffold for writing all the unit tests.
Andrei Taranchenko
Hate to tell you, but your HelloWorld is not Scala - that's just a direct translation of Java. In Scala, it's: <pre> object HelloScala extends App { println("Hello World!") } </pre>
Clayton Hunsinger
None of these examples demonstrate any actual benefits of Scala. I can create getters/setters with two clicks using just about any IDE. There's Arrays.asList() as someone else stated. There's streams which can place for loops onto a single line. Scala is just Java except you vomit on every code quality standard. Why people actually use it is beyond me.
Taleb Mohammed Housseyn
after Stream introduction in Java8 and the use of lambda expressions also the annotation base pogramming I still prefer using java then scalla if t comes to code simplicity. the question is scala better than java looking by JVM ? in other words : if JVM was a human which language would he prefer to consume Java code or Scala code and WHY ? I would adapt my self to the JVM preferences not mine, I will learn when it benefits the JVM, that what I do believe in
Harshali Patel
This is the era of Big Data, Hadoop and Spark. For those are aspiring these fields, both java and scala are important. You need to know Java for Hadoop and Scala for Spark. If you find it difficult to learn you learn Scala from these free tutorial series on Scala -
Pwndz Kigozi
Java ( Java 8+ ) seems to have advanced beyond most of the listed limitations that Scalar addresses. Post may need to be updated.
Ming Zhu
So this is what scala provide over Java? I have been using Arrays.asList("1", "2", "3"); for year. And haven't write getter and setter for years with lombok. Anything else?
Renee Sullivan
To my mind, as everything in our life now tends to be at handy and digital, you start using your mobile phone for many different purposes to make your routine easier. For developing Android applications Java is the first official programming language supported by Android Studio. That is one of the main reasons why learn Java. Here is the proof:
comments powered by Disqus