top of page

Why I Find Scala so Amazing

By Kristian Lentino

I've been on a thrilling journey with Scala for over a year and a half now. It's quite a departure from my previous life as a PHP developer navigating the labyrinthine Yii2 framework, which, to be frank, felt like a well-kept secret even in the expansive world of software development.

Can you imagine the culture shock? Concurrency? Async-what-now? These were just alien terms to me back then.

But as I delved deeper into Scala, I realized it's not a walk in the park, especially for newcomers. It's like embarking on an epic adventure where you have to decipher a multitude of concepts and unlock the secrets of the language to become truly proficient. So, here I am, still learning and conquering the fascinating universe of Scala, one challenge at a time! 🚀💡

A little bit of background

My journey with my current company embarked upon its thrilling voyage in April 2022, marking a profound departure from the well-trodden paths of my past professional experiences. This fresh expedition brims with distinctive facets that set it apart in a league of its own:

  1. Shift from Consultancy to Product Focus: Bid adieu to the world of consultancy firms, for I ventured into the heart of a product-oriented company. It was a pivotal pivot in my career trajectory, navigating uncharted waters.

  2. Global Workstage: Farewell to the cozy confines of a small, local organization! I found myself submerged in the deep waters of an international work environment, a horizon-expanding experience that broadened my perspective.

  3. Structured Workways: Here, the organizational structure and work methodologies were meticulously structured, demanding an entirely different choreography in my daily tasks. It was like dancing to a new rhythm.

  4. Tech Marvels: But perhaps the most awe-inspiring transformation was the embrace of an entirely new technology stack and a novel programming paradigm. It was akin to bidding farewell to old acquaintances and embracing the allure of the unknown.

The early stages of this adventure were accompanied by a symphony of anxiety as I grappled with adapting to these seismic shifts. To quell these tempestuous feelings, I made immersing myself in the enigmatic world of Scala my foremost mission. During those initial months, I embarked on an intensive study regimen. This voyage included traversing the hallowed pages of official documentation, enrolling in diverse courses on Coursera, and, most notably, plunging into the vast ocean of knowledge offered by Rock the JVM. Their YouTube tutorials and their paid courses on their website became my North star on this voyage of discovery. 🌟📚🚀

Time travel - 1 year and a half

Now thanks to the Trunks’s time machine we’re in the future, 1 year and a half from my starting point with Scala and I can definitely say that migrating from PHP to Scala was a wise choice for my career. With Scala I’ve learnt the true power of Super Sayan types, the almighty compiler and many many other things that in PHP didn’t existed and that we’ll discuss later.

Lets’ try to breakdown all the different aspects about this language that make me so happy to have learnt it.

  1. Type safety

Moving from a dynamically typed language like PHP (version 7.4 in my case) to Scala with its robust and strict type system is a revelation. In PHP, the flexibility of variable types can lead to a tangled web of ever-changing types, a situation that can quickly turn into a debugging nightmare. Scala's type system, on the other hand, enforces strict type checking, which eliminates the chaos and uncertainty that often plagues dynamically typed languages.

This newfound type safety is a game-changer, especially for those transitioning from languages like PHP or Python. In Python, for instance, type checks often occur at runtime, which can lead to unexpected errors slipping through the cracks. Scala's compile-time type checking catches many of these issues before code ever reaches production.

For junior developers, the contrast between PHP and Scala in terms of error-proneness is stark. PHP's permissiveness can result in numerous production issues caused by subtle type changes or unexpected null values. Scala's static typing provides a safety net that dramatically reduces such pitfalls.

In essence, Scala's type system becomes a shield against many of the common stumbling blocks encountered in dynamically typed languages, making it a compelling choice for developers seeking reliability and robustness in their code. 🛡️🚀

2. Stay Away Null!!

Another remarkable aspect of Scala, which holds a special place in my heart, is its aversion to the dreaded null reference, a notorious source of bugs and headaches in many programming languages. In Scala, null is considered a coding taboo, and instead, it offers a more elegant and safer alternative: the Option[T] monad.

The concept of null, in my humble opinion, is a breeding ground for errors. Scala takes a more principled approach by allowing you to express the presence or absence of a value explicitly. This is where the Option[T] monad comes into play. It allows you to encapsulate the idea that a value may or may not be present, neatly wrapping it in a container.

Let's illustrate this with a practical example: imagine we have the possibility of an integer (in this case, the value is indeed present and is 10) and the possibility of a string (again, the value is present and is "String"). We can effortlessly combine these options by flatmapping the values to extract them from the Monad Option and then merge them together. The result is a new Option that contains the value "String-10."

This approach not only makes your code more robust but also encourages a more expressive and self-documenting coding style. No more null-related surprises or null pointer exceptions; Scala empowers you to handle the presence or absence of values in a clean and predictable manner. 🚫🔍✨

val maybeAnInteger: Option[Int] = Some(10)
val maybeAString: Option[String] = Some("String")

val combined: Option[String] = for {
  anInteger <- MaybeAnInteger
  aString <- maybeAString
} yield s"${aString}-${anInteger}"

but what if we put to None (so the type which represent the non-presence of the value) ? Let’s try to do that!!

val maybeAnInteger: Option[Int] = Some(10)
val maybeAString: Option[String] = None

val combined: Option[String] = for {
  anInteger <- MaybeAnInteger
  aString <- maybeAString
} yield s"${aString}-${anInteger}"

The combined variable will be None since one of the two flatmapped values is None.

3. Gets the best from two worlds.

Another maybe obvious thing about why I like Scala is that it mixes in a very balanced way the functional world with the object-oriented one like for example inheritance, encapsulation and so on but with powerful and immutable classes like for example the case classes.

We have a lot of tools to generalise our code like Traits, abstract classes, companion objects which can be really useful to organise better our code and have cleaner code (apply, unapply for example).

3.1 Case classes.

Case classes are pure magic! This functionality add so much value to this language!! you can use to model your data in an elegant immutable way, they add a lof of sugar and magic in your codebase. Look at how they’re easy to understand and declare/use. They’re also eligible for inheritance. you have a lot of freedom and power in your hands!!

4. Type aliases.

This is more a way to keep the code more readable in my opinion. I use them mainly to set an alias with a more context-bound name to Scala types. Let’s give an example to be more clear. Let’s suppose we’re developing a financial app where we need to return the historical data of the last 5 days. For every date we should have a Map which contains the date as the key and the price at the end of the day as value. We can represent this things in the following way.

case class FinancialDataValues(series: Map[LocalDate, BigDecimal])

But Map[LocalDate, BigDecimal] means little to another guy who is reading the code, so maybe it’s clearer with a Type Alias which gives more context to this type (maybe the name in my example is not the clearest one 🤣🤣).

type DaysWithPrice = Map[LocalDate, BigDecimal]
case class FinancialDataValues(series: DaysWithPrice)

5. Higher kinded types.

Higher kynded types allow you to abstract over type constructors, not just concrete types.

The main benefit is that with this feature you can write very generic and modular code which can works with a lot of different scenarios. let’s see an example.

The output of this code is the following:

So basically we can create very generic code which can be used on types which wraps any (_) kind of types (they could be Int, String, LocalDate and so on).

6. Pattern matching: Love at first sight 🫶

This feature was definitely one of the most interesting when I started with Scala! I mean, it might sound like a small thing (and probably it is), but when I stumbled upon this gem, I was genuinely mind-blown! 💥

Pattern matching is, hands down, one of the crown jewels of Scala. It's like adding a sprinkle of magic to your code, making it not just readable but downright elegant. 🪄✨

Imagine this: the ability to effortlessly match a wide range of data structures, cozying up perfectly with case classes, and having support for guards like a seasoned pro. It's like having a Swiss Army knife in your developer toolkit, ready to tackle a lot of scenarios. 🧩🔍

Now, let's talk convenience! I've got a little snippet to showcase just how powerful and convenient this tool is. Trust me, in the world of PHP, this would be definitely more difficult to read! 😱😱

7. Infix notation

This is a really good feature that I think it’s a Scala’s exclusive compared to other languages: the infix notation.

Infix notation is a feature that allows you to have code written as if it was a sentence and it makes very very easy to understand the code when you're reading it, it’s like reading a sentence from some Medium blog!

Even if I heard a lot of controversial opinions about this feature, I think that if not abused they’re quite useful to improve the dev experience and readability, My 2 cents.


Looking back on my journey, I can confidently say that migrating from PHP to Scala was a wise choice for my career, probably I won’t be able to return to PHP (for the happiness of many developers 😂). It's a language that empowers developers with tools and paradigms that promote reliability, expressiveness, and elegance in code. As I continue to explore the depths of Scala, I'm excited about what the future holds in this ever-evolving programming landscape. The adventure continues, and I'm ready to face new challenges and unlock even more of Scala's secrets. 🚀💡

1 comment

1 Comment

Nice post 🙌

bottom of page