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
def veryTall: Boolean = height match {
case Some(h) => h > 7
case _ => false
}
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
def veryTall:Boolean = height.exists(_> 7)
Example 2
How about a piece of logic, which needs to return true when Option is `None`
Usual Code
. Lets say this code…
def avgHeight: Boolean = height match {
case Some(h) => h < 7 && h > 5
case _ => true
}
Better Version
Above looks nice and to the point. But it can be more concise and readable. Have a look
def avgTall:Boolean = height.forall{ h => h < 7 && h > 5}
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
if (ids.length > 0) {
readFromDB(ids.head)
} else {
None
}
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.
ids.headOption.flatMap(readFromDB)
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
val recordList = scala.collection.mutable.Buffer[Entry]()
getNames().foreach { name =>
recordList.append(createEntry(name))
}
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
getNames.map(createEntry)
Simple and precise
Example 5
Not using getOrElse
!!!
Usual Code
if (resultList.isEmpty) defaultResult else resultList.head
Better Version
resultList.headOption.getOrElse(defaultResult)
Example 6
Null
check, ah its a killer.
Usual Code
if (record == null) defaultName else record.name
Better Version
Option(record).map(_.name).getOrElse(defaultName)
This is all for this post. Please share your thoughts.