Scala Style: Real Life Code — Post 6

This blog post is a continuation of previous posts I wrote about scala. I realized that those were more text book.

We do not do matrix multiplication in our day to day job, neither we merge arrays. Life is too easy. We write simple code. How to do that with Scala. In this short post I will cover some such example. I will write real life scala code .. and try to see how we can improve it.

In a following post I will write about dreaded foldLeft, scanLeft & reduceLeft.

Example 1

Let’s start with Option. Once you start writing code in scala.. you may use Option and do various comparisons. You may like code like this

Usual Code

This looks reasonable. So does following
def veryTall: Boolean = height.map(_ > 7).getOrElse(false)

Better Version

But this all too much code. Scala enables you to write less code which is more readable. Have a look, following is same logic but better code in my opinion

Example 2

How about a piece of logic, which needs to return true when Option is `None`

Usual Code
. Lets say this code…

Better Version

Above looks nice and to the point. But it can be more concise and readable. Have a look

Example 3

We have a list of ids and if it is non empty we need to take first id and read record from DB else none. assume readFromDB(id: Int): Option[Record] is method which reads from db.

Usual Code

I see people doing it like this

Better Version
above works.. but a better version can be. This will make you understand why we have flatMap .. it flattens. If it is option inside option.. flatMap will get rid of outer option.

Example 4

You have a list of params and you need to create list of objects from them. Lets say getName gives a list of name, and createEntry writes to table.

Usual Code
I used to think it may not happen, but I have seen this code countless times

Better Version
Above code is result of context developer carry from java or C++. Thats the way you solve such problem theirs. But Scala it can be re written like

Simple and precise

Example 5

Not using getOrElse !!!

Usual Code

Better Version

Example 6

Null check, ah its a killer.

Usual Code

Better Version

This is all for this post. Please share your thoughts.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store