Coding Style

Scala Comments

In this blog post, you’ll learn about -

Coding Style for better readability.

This post gives a good overview on Scala’s style guide. Here are some additional guides that I’ve used for better readability -

1. Use Pattern Matching for Collection functions like map, filter, flatMap -

val numbers : List[Int] = List(1,2,3) val squares : List[Int] = numbers.map(n => n * n) // bad naming and no data types val squares : List[Int] = numbers.map{case number :Int => number * number} // pattern matching syntax makes it more readble.

2. Avoid return statements when possible

In scala, return statements are optional and hence should be avoided when possible.

3. Avoid using variables or vars

Make your variables immutable, unless there’s a good reason not to.

**4. Don’t use _ **

Although _ is a cool way to write quick code, avoid using them and substitute them with more meaningful variable names.

**5. Avoid chaining more than 5 functions at a time ** -

One way to build monads is through chaining. Consider the example -

val derivedList = list.map(x => ???).filter(x => ???).reduce(reduceFunc).map(x => ???).sum.map(x => ???)

After a lot of chaining, this gets hard to read and follow. Use intermediate variables.

Kaushik Rangadurai

Code. Learn. Explore

Share this post

Comments