Hello,
Java is 28 years old, but Scala is 19 years old. I don’t want to use age as a reason for being good, but Java is more mature and runs on more than 5.5 billion devices. Scala uses Java Virtual Machine and I want to know why anyone should prefer Scala over Java? Security, speed, simplicity or… What is the reason for using Scala instead of Java?
I think that someone who has experience programming in Java and then migrated to Scala can give the best answer.
much more powerful type system, which opens possibility to design libraries a lot more sophisticated than in java, while being fully type safe - that includes implicits/ givens and new metaprogramming in scala 3
efficient functional collections in standard library, i.e. immutable collections with structural sharing Persistent data structure - Wikipedia that are vital for true functional programming, i.e. programming style that avoids side effects (as opposed to naive intepretations like ‘functional programming is about using any sort of functions’)
java collections do not support structural sharing, because their immutable collections throw exceptions when you want to e.g. add elements to them. functional collections instead return a new collection which includes both new element and elements from old collection.
java authors said they won’t add functional collections to java, because they fear explosion of interfaces. they want to have simple collections hierarchy, but that effectively closes the door for functional collections. there are projects like vavr.io that provide functional collections Vavr User Guide, but they’re incompatible with the java collection interfaces and probably are not very popular.
in short, in my opinion java is ill-suited for functional programming (i.e. programming style where you avoid side effects), because of both wrong collections interfaces in standard library and ubiquitous imperative programming style, which you would have to fight if you want to embrace functional programming.
if you don’t care about functional programming (i.e. you’re not keen on learning and using its benefits) then scala is probably not a great choice for you, i think. kotlin would probably be better if you want to stick to imperative style full of side effects. otoh, if you want to use functional programming often and much more broadly than in java, but still be compatible with java ecosystem, then switching to scala would be great choice.
That depends on, among other things, whether you are working independently or on a team. I work independently, developing research prototype software in support of my own ideas about air traffic control automation (for both conventional aviation and the new urban air mobility concepts).
I have been using Scala for many years now, and when I was forced on rare ocassion to write Java code I hated it. If I were forced to use Java exclusively, I would just quit coding altogether and try to find something else useful to do (my job does not require that I write any code at all).
As a compulsive minimalist, the choice was easy for me. The lack of semicolons required at the end of each line was enough to convince me. In Scala 3, the lack of braces everywhere would be enough by itself to convince me as well.
When I looked at some some of my colleagues Java code a few years ago, I was seriously annoyed by the level of boilerplate that cluttered their code. I’m thinking specifically about “getters” and “setters”. Scala avoids all that useless crap with the simple idea of the uniform access principle. Unless or until Java adopts that concept, I consider that alone another sufficient reason to choose Scala over Java.
I also find Scala to be more expressive, allowing me to go more directly from concept to code. Without all the excessive baggage, it’s more like the “pseudocode” that is used to define and explain an algorithm. It is like a scripting language with the performance and scalability of a compiled language.
As an earlier responder explained, the immutable collections are also very useful once you learn how to use them. And they make the step from single-threaded to basic parallel processing almost trivial, without having to worry about race conditions.
Scala has a reputation for being complicated, but I think that is misleading. Yes, it may be complicated for doing complicated things, but for the kind of work I do, it is about as simple as it can be and still get the job done.
The two-word answer to your question is “functional programming”. I expanded on that a little at Foreword - Programming Scala, 3rd Edition [Book] — but only a little. There’s a lot more meaning in those two words than meets the eye. There’s a whole world in there, really. Many people, once they’ve spent enough time in that world to get to know it, never want to go back to the kind of programming they first learned.
I agree with the other responses that have been posted, but I’d like to add that Scala isn’t only a JVM language. You can also target JavaScript (Scala.js) or compile directly to native code (Scala Native).
I have used Java since 1995 and Scala since 2005, and dabbled in Kotlin for over five years. While Scala is my favourite language because of its power and expressiveness, I only use it for personal projects now. I find too many people abuse Scala… “With great power comes great responsibility,” and in my opinion, I have not seen enough people responsible enough to use Scala for anything other than research projects. If I sound elitist, it’s due to being trolled too many times by ‘Scala Experts’ who cannot take honest criticism. I suggest that Kotlin was a good response to those people.
Scala has made incredible advances in thought and innovation, advanced the design and evolution of Java, and inspired the creation of Kotlin. I like to think that Kotlin is a fork of Scala, and its Android adoption proves the commercial suitability of Kotlin. People tell me that Kotlin has 80% of the power of Scala with only 20% of the features.
Often we learn more from our failures than our successes, and I have learned a lot from Scala’s failures. Still, it’s my favourite programming language. It is the “kitchen sink” language that James Gosling talked about, and always welcome in my kitchen.
Is Scala DICEE?
DICEE is an acronym that was coined by Guy Kawasaki, who became famous as a developer evangelist for the original Apple Macintosh team. He says that great products are DICEE, meaning Deep, Indulgent, Complete, Elegant, and Emotive:
Deep: The product doesn’t run out of features and functionality after a few weeks of use. Its creators have anticipated what you’ll need once you come up to speed. As your demands get more sophisticated, you won’t need a different product.
Indulgent: A great product is a luxury. It makes you feel special when you buy it (and use it).
Complete: A great product is more than a physical thing. Documentation counts. Customer service counts. Tech support counts.
Elegant: A great product has an elegant user interface. Things work the way you’d think they would. A great product doesn’t fight you, it enhances you.
Emotive: A great product incites you to action. It is so deep, indulgent, complete, and elegant that it compels you to tell other people about it. You’re bringing the good news to help others, not yourself.
Two years after discovering Scala — way back in 2013 — I came to the conclusion that
it meets the definition of DICEE, and I think it’s just as true today:
Scala is deep: After all these years I continue to learn new techniques to write better code.
Scala is indulgent: Just like Ruby, I feel special and fortunate to use a language that’s so well thought out.
Scala is complete: The documentation is excellent, terrific frameworks exist, and the support groups are terrific.
Scala is elegant: Once you grasp its main concepts you’ll fall in love with how it works just like you expect it to.
Scala is emotive: Everyone who works with it wants to tell you how special it is. Myself, I had never written a programming book in my life, but by 2012 I was eagerly mailing people at O’Reilly to tell them how much I wanted to write the Scala Cookbook.
As I write this book many years later I hope to share not just the nuts and bolts of the Scala language, but also its elegance and the joy of using it.
A programming language obeys the Curry-Howard correspondence with logic if for any types A, B, the language also contains composite types corresponding to the logical formulas “A or B”, “A and B”, “A implies B”. In Scala, these composite types are Either[A, B], the tuple (A,B), and the function type A => B. All modern functional languages such as OCaml, Haskell, Scala, F#, Swift, Elm, and PureScript support these three type constructions and thus obey the CH correspondence. Having a complete logic in a language’s type system enables declarative domain-driven code design.
It is interesting to note that most older programming languages (C/C++, Java, JavaScript, Python) do not support some of these composite types. In other words, these programming languages have type systems based on an incomplete logic. As a result, users of these languages have to implement burdensome workarounds that make for error-prone code. Failure to follow mathematical principles has real costs.
No, Scala is suitable for functional, object-oriented, and imperative programming. But usually does not “stick” to any one of these paradigms, rather it combines them. This is known as “multi-paradigm”. (What the commenters above me were trying to say is that, in the Java / OOP world, it’s difficult to do functional programming without a language like Scala.)
A good example of this is the Parallel Programming course I’ve taken on Coursera. We make an image blurring program. There, object-oriented programming is used for the overall organization of the code, functional programming is used for most of the logic and parallelization, and, where it’s needed for performance reasons, while loops and mutation (imperative programming) are used. All in the same code base.
Yes. Scala is completely interoperable with Java. It has all the features of Java, plus a lot more. Please read Programming in Scala 5th edition which is written mostly from a Java programmer’s perspective coming to Scala. It shows how Scala does everything Java does, and improves upon them.
Scala takes a while to really appreciate, a few questions here and there won’t do it justice. You should dive into it. Best book for beginners in my opinion is Get Programming with Scala which, again, is written for someone with a bit of Java experience.
Edit: Just to add, I was coming from the other (functional) direction: “Why Scala instead of Haskell?” and I disliked it at first (was a strong Java / OOP hater). It took me a while to appreciate Scala, and even warmed me towards Java.
In addition to everything just stated, Scala provides a multitude of features that make it a unique and truly modern programming language:
It’s created by Martin Odersky—the “father” of javac—and influenced by Java, Ruby, Smalltalk, ML, Haskell, Python, Erlang, and others.
It’s a high-level programming language.
It has a concise, readable syntax—we call it expressive.
It’s statically typed—so you get to enjoy all the benefits of static type safety—but it feels like a dynamic scripting language.
It’s a pure object-oriented programming (OOP) language; every variable is an object, and every operator is a method.
It’s also a functional programming (FP) language, so you can pass functions around as variables.
Indeed, the essence of Scala is, as Mr. Odersky puts it, that it’s a fusion of FP and OOP in a typed setting, with:
Functions for the logic
Objects for the modularity
It runs on the JVM, and thanks to the Scala.js project, it’s also a type-safe JavaScript replacement.
It interacts seamlessly with Java and other JVM libraries.
Thanks to GraalVM and Scala Native, you can now create fast-starting native executables from your Scala code.
The innovative Scala collections library has dozens of prebuilt functional methods to save you time and greatly reduces the need to write custom for loops and algorithms.
Programming best practices are built into Scala, which favors immutability, anonymous functions, higher-order functions, pattern matching, classes that cannot be extended by default, and much more.
The Scala ecosystem offers the most modern FP libraries in the world.
One thing that I love about Scala is that if you’re familiar with Java, you can be productive with Scala on day 1—but the language is deep, so as you go along you’ll keep learning and finding newer, better ways to write code. Scala will change the way you think about programming—and that’s a good thing.
Of all of Scala’s benefits, what I like best is that it lets you write concise, readable code. The time a programmer spends reading code compared to the time spent writing code is said to be at least a 10:1 ratio, so writing code that’s concise and readable is a big deal.
Scala doesn’t require you to leap backwards off the Java platform to step forward from the Java language. It allows you to add value to existing code—to build on what you already have—because it was designed for seamless interoperability with Java. Scala programs compile to JVM bytecodes. Their run-time performance is usually on par with Java programs. Scala code can call Java methods, access Java fields, inherit from Java classes, and implement Java interfaces. None of this requires special syntax, explicit interface descriptions, or glue code. In fact, almost all Scala code makes heavy use of Java libraries, often without programmers being aware of this fact.
Another aspect of full interoperability is that Scala heavily re-uses Java types. Scala’s Ints are represented as Java primitive integers of type int, Floats are represented as floats, Booleans as booleans, and so on. Scala arrays are mapped to Java arrays. Scala also re-uses many of the standard
Java library types. For instance, the type of a string literal “abc” in Scala is java.lang.String, and a thrown exception must be a subclass of java.lang.Throwable.
Scala not only re-uses Java’s types, but also “dresses them up” to make them nicer. For instance, Scala’s strings support methods like toInt or toFloat, which convert the string to an integer or floating-point number. So you can write str.toInt instead of Integer.parseInt(str). How can this be achieved without breaking interoperability? Java’s String class certainly has no toInt method! In fact, Scala has a very general solution to solve this tension between advanced library design and interoperability. Scala lets you define rich extensions, which are always applied when non- existing members are selected.10 In the case above, when looking for a toInt method on a string, the Scala compiler will find no such member of class String, but it will find an implicit conversion that converts a Java String to an instance of the Scala class StringOps, which does define such a member. The conversion will then be applied implicitly before performing the toInt operation.
Scala code can also be invoked from Java code. This is sometimes a bit more subtle, because Scala is a richer language than Java, so some of Scala’s more advanced features need to be encoded before they can be mapped to Java. The details will be explained in Advanced Programming in Scala.
Scala programs tend to be short. Scala programmers have reported reductions in number of lines of up to a factor of ten compared to Java. These might be extreme cases. A more conservative estimate would be that a typical Scala program should have about half the number of lines of the same program written in Java. Fewer lines of code mean not only less typing, but also less effort at reading and understanding programs and fewer possibilities of defects. There are several factors that contribute to this reduction in lines of code.
First, Scala’s syntax avoids some of the boilerplate that burdens Java programs. For instance, semicolons are optional in Scala and are usually left out. There are also several other areas where Scala’s syntax is less noisy. As an example, compare how you write classes and constructors in Java and Scala. In Java, a class with a constructor often looks like this:
class MyClass { // this is Java
private int index;
private String name;
public MyClass(int index, String name) {
this.index = index;
this.name = name;
}
}
In Scala, you would likely write this instead:
class MyClass(index: Int, name: String)
Given this code, the Scala compiler will produce a class that has two private instance variables, an Int named index and a String named name, and a constructor that takes initial values for those variables as parameters. The code of this constructor will initialize the two instance variables with the values passed as parameters. In short, you get essentially the same functionality as the more verbose Java version. The Scala class is quicker to write, easier to read, and most importantly, less error prone than the Java class.
Scala’s type inference is another factor that contributes to its conciseness. Repetitive type information can be left out, so programs become less cluttered and more readable.
But probably the most important key to compact code is code you don’t have to write because it is done in a library for you. Scala gives you many tools to define powerful libraries that let you capture and factor out common behavior. For instance, different aspects of library classes can be separated out into traits, which can then be mixed together in flexible ways. Or, library methods can be parameterized with operations, which lets you define constructs that are, in effect, your own control structures. Together, these constructs allow the definition of libraries that are both high-level and flexible to use.
Hello! I’m going to do some necromancy on this thread because I was googling for “why would anyone use scala” in a burst of frustration and this popped up in the second slot. So obviously this is an important topic to the rest of the world (note that I did not use the word “Java” in the search query).
I’ve been programming with Java since 1996 and I think of myself as a pragmatist instead of an OO or functional programmer or Java evangelist. I use what gets the job done best and I am fully aware that the restrictions on who does the job greatly affects what is the best tool. I’ve been recently learning Scala because I need some new stuff to fill the tool box with and it’s not a very great leap away from the Java ecosystem I am so familiar with.
Anyway, there was some comments that I think were, um, maybe a bit ill-advised.
This is semantically a slightly incorrect as Java collections do not even claim to be “immutable.” They claim to be “unmodifiable” meaning that the party holding the reference to the collection cannot change it. If someone else holds the reference to the original underlying structure, the collection can still change.
This is not a fear, but a fact. Even when the hierarchy was designed from the ground up to be compatible with immutability, we ended up with that. The immutable side of Scala’s collection hierarchy is so much cleaner. Java lost this game already in the start because there was never much desire to even attempt any compatibility with immutability and retrofitting it would result in an incoherent mess.
I have a hard time believing this, as I am reading your perfectly punctuated comment that is very cleanly split into paragraphs. And the amount of times the semicolon gets brought up is just mind boggling to me as a perfectly valid reason to choose a language. A semicolon is like a stop at the end of a sentence. Regardless of whether I write English or Java, I don’t pay any attention to punctuation. Typing them is an automated habit that just happens. (And don’t comment about my mistakes in punctuation. English is only my third language after my native tongue and Java.)
Yes, they can be a bit of a pain. Records fix them to some extent (thanks to Scala). Then again a massive amount of getters and setters in a non-DAO class seems like a code smell. And for DAOs, we just autogenerate and forget them. They’re not really something we type out one by one.
There are annotation based solutions to fix that. Reliance on annotations to implement language features is a big miss for the Java “ecosystem” as they are often used to implement features that throw everything we gained from static typing straight into the trash can.
If we’re going to use corporate adoption as an argument we have to also address Scala’s failure in it, but I won’t do it because I don’t think it’s an argument at all. Kotlin was chosen as the default language for Android because Google needed a language they could control in case the Oracle Java-law suit went nuclear. Kotlin doesn’t exist because it’s a good language. It’s continued reason to existence is only to be a legal fail safe in a battle between two mega-corporations.
You must realize how much that sounds like cult, right?
Concise is not exactly the same as readable. What I like in Java is that the language designers have taken a lot of effort to minimize the amount of meaning placed on different punctuation marks. Almost everything is written in plain English with words that already have a meaning established in the spoken language we use. When punctuation is used to represent complex concepts in a syntax, the code becomes less readable as the reader has to first learn what each punctuation mark means. Perl died because the language ran out of punctuation marks and couldn’t evolve anymore.
Sure humans can learn complicated things. Look at skateboarders or foiling kite surfers for examples. But I for one don’t want to spend my time memorizing endless punctuation marks. The punctuation marks don’t give me a feeling of satisfaction, the concepts behind them do and I want to concentrate on them.
Anyway, I will keep on learning this language and I will expect to come back and laugh at this post in a couple of years.
While I totally agree with this, there is a sweet spot between too much syntax that it is boilerplate and the intent gets lost, and too few characters and a lot of compiler magic that you need to learn a lot in order to get it.
Also, during the last few months I realized that such sweet spot is different for each individual (one of those things that feel obvious in retrospect but my younger self was sure it was objectively correct).
For me though, Scala for the most part hits that sweet spot, where I feel like the language allows me to express what I want and the effort needed to understand it is not that much. But, there are times, however, when I feel it gets a bit short, as well as times when I feel that either I or another person went too far and the code is complicated.
That in fact is the biggest win and lose of Scala it is very flexible, meaning that it allows for both the best and worst code I have seen.
All I can tell you is that, usually, when I have to use any other language for whatever reason, I always feel constrained and that I have to do everything in a “dumb” way because the language doesn’t have the tools I am already used to (which I am sure happens with folks used to other languages when learning Scala). The lack of immutable values, immutable collections, utility types like Option and Either, ADTs, pattern matching, good lambdas, etc are usually the reason, but that is hard to explain.
Also, for the record, I am a happy IO user. I personally believe that as of today “Programs as Values” is the best paradigm to tackle concurrency. Thus, when writing in concurrent heavy code I prefer to use Scala with the typelevel ecosystem. Which, in turn, is what I do for a living. If I were working in other contexts, I may pick either other ecosystems or other languages.
Anyways, welcome to the community, good luck with your learning and feel free to ask as many questions as you may have. We are usually happy to help
I would recommend joining the Discord server if you want to chat about stuff and ask questions in a more lightweight manner: Scala
Indeed it is.
Join to the (dark)FP side, we have cookies and cats
Absolutely true (I grew up in the days when APL, the original “write-only language”, was still a living memory), but it’s worth noting that “concise” here is (IMO) less about syntax, and more about factoring.
To me, the absolute A-number-1 reason why I love Scala is that it provides the best refactoring capabilities of any language I’ve ever worked in. (Something like 40 of them, over the years.) Having access to both full-featured OO and FP machinery in the language means that I can refactor out almost every pattern I see in my code.
The result is that my code tends to wind up relatively low-boilerplate and low-duplication; that in turn means that it is easier to maintain and enhance the code. That’s a big win, in my book.
There is room to disagree about which way you want to style your code – personally, I kind of like my curly braces, and find them easier to read than the more-concise (but arguably a bit more complex) indentation-based style that came in with Scala 3. But that refactoring power is helpful in pretty much any codebase.
Yes, just as I imagine you must realise that reading those statements by Alvin Alexander in isolation (out of context) helps make them sound cult-like.
The opposite seems true about reading them in context, i.e. as examples of the following:
Indulgent: A great product is a luxury. It makes you feel special when you buy it (and use it).
Emotive: A great product incites you to action. It is so deep, indulgent, complete, and elegant that it compels you to tell other people about it. You’re bringing the good news to help others, not yourself.
As for concision in itself, the latest version of ‘Programming in Scala’ still contains the following example, which reminds me of the idea that quantity has a quality all of its own:
Scala programs tend to be short. Scala programmers have reported reductions in number of lines of up to a factor of ten compared to Java. These might be extreme cases. A more conservative estimate would be that a typical Scala program should have about half the number of lines of the same program written in Java. Fewer lines of code mean not only less typing, but also less effort at reading and understanding programs and fewer possibilities of defects. There are several factors that contribute to this reduction in lines of code.
In Java, a class with a constructor often looks like this:
class MyClass { // this is Java
private int index;
private String name;
public MyClass(int index, String name) {
this.index = index;
this.name = name;
}
}
Regarding semicolons, the latest version of ‘Programming in Scala’ still contains the following example
echoargs.scala:
@main def m(args: String*) =
var i = 0
while i < args.length do
if i != 0 then
print(" ")
print(args(i))
i += 1
println()
Note that in Scala, unlike in Java, you need not put the boolean expression for a while or an if in parentheses. Another difference from Java is that you can optionally leave off the curly braces on a block, even if it has more than one statement, so long as you indent each line appropriately.
And although you haven’t seen any of them, Scala does use semicolons to separate statements as in Java, except that in Scala the semicolons are very often optional, giving some welcome relief to your right little finger. If you had been in a more verbose mood, therefore, you could have written the echoargs.scala script more in a Java style as follows:
@main def m(args: String*) = {
var i = 0;
while (i < args.length) {
if (i != 0) {
print(" ");
}
print(args(i));
i += 1;
}
println();
}
As of Scala 3, the indentation-based style, called “quiet syntax,” is recommended over the curly brace style. Scala 3 also introduced end markers, to make it easier to see where larger indented regions end. End markers consist of the keyword end followed by a specifier token, which is either an identifier or a keyword.
I have seen this MyClass example before and I don’t think it’s a fair representation of either language.
The Java example that most closest matches that Scala class would be this quite useless piece of code:
public class MyClass {
public MyClass(int index, String name) {
}
}
To be even remote useful, the Scala example should be:
class MyClass(val index: Int, val name: String)
Java equivalent then becomes this:
public record MyClass(int index, String name) { }
The Java code is only two characters longer but those two characters are quite meaningless because the record tilts the scales completely. The Scala example doesn’t come anywhere near the usefulness of the Java equivalent anymore. The Scala example that would be the equivalent of the Java record becomes this:
class MyClass(val index: Int, val name: String) {
private def canEqual(other: Any): Boolean = other.isInstanceOf[MyClass]
override def equals(other: Any): Boolean = other match
case that: MyClass =>
that.canEqual(this) &&
index == that.index &&
name == that.name
case _ => false
override def hashCode(): Int =
val state = Seq(index, name)
state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
}
I didn’t write that. I autogenerated it with an IDE, so feel free to improve it. And pardon the brackets, my IDE doesn’t understand the latest Scala features yet so it can’t autogenerate code to a class that doesn’t have a body.
Anyway, what I think we can get out of this is that trivialized examples are quite useless as masurement sticks of languages intended for “real work.”