Why Scala instead of Java?

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.

Please answer briefly.

Thank you.

4 Likes

some quick thoughts:

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

4 Likes

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.

2 Likes

Is this a quote from a marketing brochure?

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

3 Likes

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.

7 Likes

Hello all,
Thank you so much for all the replies.
I have two questions:

1- So, Scala is only suitable for functional programming?

2- Can Scala have all the features and capabilities of Java?

From https://alvinalexander.com/downloads/scala/HelloScala.pdf

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.

Alvin Alexander

2 Likes

From GitHub - winitzki/sofp: A free book: "The Science of Functional Programming"

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.

Java is not a functional programming language:

1 Like

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.

1 Like

So, Scala is only suitable for functional programming?

From Scala Cookbook, 2nd Edition:

Scala Features

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.

1 Like

Can Scala have all the features and capabilities of Java?

From Programming in Scala, Fifth Edition:

Scala is compatible

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.

From Programming in Scala, Fifth Edition:

Scala is concise

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.

1 Like