Java – Why Use Scala over Java

javascala

I am totally into Scala as a language … and still I struggle with why any company should switch from Java to Scala. Is Scala just syntatic sugar on top of the JVM or are there fundamental improvements in Scala over Java that would improve real world applications?

Best Answer

Disclaimer: I'm not a Scala guru.

Scala does two things extremely well which Java (currently) does not.

Solve functional problems

  • At the most basic level, Scala has fully fledged closures with collections support. This means you no longer have to write boiler plate code such as (shamelessly ripped off a DZone post)

    public List<Item> bought(User user)
    {
        List<Item> result = new ArrayList();
        for (Item item : currentItems)
        {
            if (user.bought(item))
            {
                result.add(item);
            }
        }
        return result;
    }
    

But instead write something like:

def bought(user: User) = items.filter(user bought _)
  • There's more functional love, but I'm not qualified to talk about it since I currently still suck at functional programming :)

Solve concurrency in a safer way

  • Scala has an actors model (+ some other goodness) which is inheritly safer than Java's mutable data + locks on Thread model (no matter how good the libs are getting, Java is still hindered by the language).

I can't honestly think of too much else that makes Scala stand head and shoulders above Java. Lots of small gains and improvements yes, but also far more rope to hang yourself with. YMMV

HTH a little