About seven or eight months I got the opportunity to support an application written in Scala. It had been a long time since I had learnt a new programming language and I had been interested in Scala for a while so I decided to go for it. I thought I’d note down a few things I’ve noticed whilst learning Scala coming from a Java background.
My programming history started with Perl before I learnt and got a job in Java so I’m used to expressive languages. I certainly understand people’s criticism of Java being too verbose. IDEs, libraries and newer versions are helping with this but the language wasn’t built with these from the start so they can feel a little tacked on. Scala is filled with syntactic sugar and functional paradigms that encourage more readable and expressive code.
For example, in ScalaTest we can have the following assert in our unit test:
pub must not be None
Whereas in a Java JUnit test we have:
Or if we use one of the matcher libraries to make it read better:
Functional programming definitely takes a change in thinking when coming from OOP. Recursion is one of those things that I use so rarely that it always takes a bit of work to get my head in that space again.
Not throwing exceptions requires thinking about problems slightly differently. In Java, Spring MVC makes exception handling really easy by allowing you to map exception handlers to HTTP response codes. You can then just throw an exception to return whatever response you like. In FP you shouldn’t throw exceptions. But as FP is baked into Scala there are classes like
Either that allow the return of exceptional data or when working with asynchronous code then
Luckily I’ve spent the last couple of years embracing a few of the tenants of FP in my Java programming. Things like immutable classes, immutable data structures and marking variables as
final has helped me write cleaner code. Java 8 has also helped by providing
reduce, etc on Collection classes so it’s been easier to work with immutable data structures.
Missing Spring Boot
I’ve been using the Play Framework for building web apps in Scala which seems to be the popular choice. It’s serviceable but my recent heavy use of Spring Boot has completely spoilt me. Spring Boot is such a great framework that provides so much for free. It would probably be the biggest reason for me choosing Java over Scala for a side project.
subscribe via RSS