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:

Java:

List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");

Scala:

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:

Java:

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

Scala:

val ints = list.map(s => s.toInt)

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

A Class Example: Scala vs. Java

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) {
        this.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) {
        this.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) {
        this.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("User.name cannot be null!")
        }
        _name = name
    }

And you can still set the name like this:

user.name = "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) {
        products.addAll(order.getProducts());
    }
    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())) {
                products.add(product);
            }
        }
    }
    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.

Wrap-up

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?”

About the author

Matt Hicks, United States
member since February 4, 2014
Matt is a top architect and developer who has architected, developed, and maintained systems and software applications with companies large and small around the world. He has extensive experience with web, mobile, desktop, and even game development. [click to continue...]
Hiring? Meet the Top 10 Freelance Scala Developers for Hire in December 2016

Comments

HammerOfTruth
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!
DFA1
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 n Scala ! I like Scala, but about Java vs Scala example, some functional trick is possible on Java 8 now...
HammerOfTruth
Also there is a compile error in your infographic. You may need to add an argument of type Order to the getProducts method.
Josip
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.
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.
S.Karthik
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.
Josip
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.
Xavier Carpentier
It's not wrong :)
Jose Luis Diaz
I agree.
Wael Chaabane
Thx man this is really Helpfull
darkcg
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 particularly good at something, but, at the end of the day, my bills are paid by Java.
darkcg
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. :)
zarthross
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).
Corrie Engelbrecht
You say "this entirely removes the need to pre-configure method accessors". Fair enough. However, when you compare two classes, one in Java and one in Scala, both with getters and setters that have logic in them, what did you win with Scala? Nothing. This is not a good example. The comparison between a Java class with getter and setter methods because you might need logic in descendant classes with Scala classes that don't implement any logic for getters and setters is pointless.
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 sometimes 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
Mehdi
"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." Bullshit! Didn't read any further.
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 (http://www.scala-lang.org/old/node/2447.html)
Channing Walton
It has indeed been fixed.
Peter
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?
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
Lê Anh Quân
For those who curious about Scala vs Java 8, here is a valuable post at StackOverFlow: http://stackoverflow.com/questions/13707809/java-8-and-scala/13708335#13708335 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.
stepanian
I agree. By code "optimizing" I assume you mean reducing code size not 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.
laker
so you value a new technique by its popularity? you should really not learn scalar then.
guessman
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!
ches
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.
ches
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 :-)
Corrie Engelbrecht
And in short: the key point that I was making was that this is not illustrated properly in the article.
ches
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="http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/">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="http://www.scala-js.org/">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="https://github.com/japgolly/scalajs-react">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="http://akka.io/">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.
ches
I was trying to be helpful, to you if you genuinely didn't understand, or to other readers. You're welcome :-P
Corrie Engelbrecht
I wasn't thanking you, actually. Perhaps you can be helpful by posting proper examples, which is what people actually need. All you've done was to restate pretty much verbatim what the article's author wrote. So I think you were just trying to draw attention with the appearance of being helpful.
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?
ches
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.
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. http://www.quora.com/Is-Groovy-going-away
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 }
Levent
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.
Corrie Engelbrecht
Perhaps you can cite a source for your statement about best practices, and at the same time explain what you believe "logic inside getters" actually refers to. if you look at the examples in the article, you will find a snippet that's equally applicable to Java and Scala: def name_=(name: String) = { if (name == null) { throw new NullPointerException("User.name cannot be null!") } _name = name } That accessor contains logic. What do you have to say about that?
Rudro
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])
jpartogi
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.
Alex Aiezza
Sorry folks, but especially with Java 8 on the loose, this will never be taken seriously by professionals. Scala is toy for inexperienced developers; nothing more. It belongs on a shelf along with the Play Framework, PHP, CoffeeScript & Perl. It takes 2 seconds to Google: "Java Best Practices". There's a difference between lack-of-productivity-due-to-an-over-complicated tool and laziness from a lack of respect for Java best practices. No offense Matt Hicks, but I think we can do better than this.
Julian S
I think this article just convinced me to learn some scala.
nick
bloody fool
nick
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.
Dr_Truth
.. or just use a struct in C or C++ and don't bother with empty, useless accessors on value objects in the first place..
Dr_Truth
Exactly. The world doesn't need yet another method to dig a ditch. No value here.
ches
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.
Guest
Its clear that you nothing about oop. Gain some experience first.
Dr_Truth
Its clear that you know nothing about oop, but you certainly love pretending you do.
ches
Shouldn't have fed the troll. Live long and prosper, my bitter, bridge-dwelling friend.
kasra
what about working with xml in scala? :D
boniatillo.com
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 = list.map(s => s.toInt) can be written as : val ints = list.map(_.toInt) - I think it is important to learn Scala because of on going projects such as : Spark and Kafka
LoiX
The most important question is... Why the Java developer has a old screen and the Scala developer has a nice laptop? :D Good article!
allObjects
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.
Zerh
Apparently at that time (when he wrote the post) he never learned that this is possible in Java: Stream<Products> p = orders.stream().flatMap(o -> o.getProducts().stream()) or... instead of getProductsByCategory method orders.stream().flatMap(o -> o.getProducts().stream()).filter(p -> p.getCategory().equals(category)) or... Arrays.asList("a", "b", "c");
Edward Beckett
Java 8 > List<String> list = stream.collect(Collectors.toList());
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.
john
"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.
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 http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
Chikoz
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: http://yz.mit.edu/wp/true-scala-complexity/ 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?
LOL
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 (http://javaslang.com). 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
OlegM
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.
john
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.
john
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...
john
definitely learn JAVA first as Scala is the next evolution(in certain ways) to JAVA.
ScalaCourses.com
ScalaCourses.com is an excellent resource for learning Scala and Play Framework. Learn more at GetScala.com
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.
nafg
Neither do they know Scala, so that isn't a distinction
Artiom Lukianov
Why not Kotlin?
aa
Niceeee post.........Thumbs upp
aa
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.
Zerh
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. http://www.tiobe.com/tiobe_index
OrbitManual
def products = orders.flatMap(_.products)
JAC_JustAnotherCoder
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
Mark
"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 http://redwerk.com/technologies/scala-development At each project with Scala at Redwerk, I feel that I've made the right choice to learn this nice powerful programming language!
Walter
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");
dk14
"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.
JAY-K
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.
Octavian
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.
nrkkalyan
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.
comments powered by Disqus
Subscribe
The #1 Blog for Engineers
Get the latest content first.
No spam. Just great engineering and design posts.
The #1 Blog for Engineers
Get the latest content first.
Thank you for subscribing!
You can edit your subscription preferences here.
Trending articles
Relevant technologies
About the author
Matt Hicks
HTML5 Developer
Matt is a top architect and developer who has architected, developed, and maintained systems and software applications with companies large and small around the world. He has extensive experience with web, mobile, desktop, and even game development.