Home » JVM Languages » Scala » Scala Wonderland: The functional style

About Rado Buransky

Rado Buransky

Scala Wonderland: The functional style

Scala encourages to use a functional style of programming. For programmers coming from imperative world of Java or C# it is the main challenge. The first step is to recognize the difference between functional and imperative programming. Scala has two keywords for variable declaration:

  • var – mutable variables
  • val – immutable variables

One sign of imperative sign is occurence of var in the code. Scala encourages to lean towards val, but use whatever is appropriate for the given situation.
Example of imperative style:

def printArgs(args: Array[String]): Unit = {
  var i = 0
  while (i < args.length) {
    i += 1

More functional style:

def printArgs(args: Array[String]): Unit = {

Here you can see the reason why Scala encourages functional style. It helps you to write clearer, more understandable and less error-prone code. But you can do it even better. The refactored method is not purely functional. It has side effects – it prints to the standard output stream. One sign of a function with side effects is that its result type is Unit. If a function doesn’t return any value, it has either side effects or it is useless.

The most functional solution:

def formatArgs(args: Array[String]) = args.mkString("\n")

Prefer vals, immutable objects and methods without side effects.

Reference: Scala Wonderland: The functional style from our JCG partner Rado Buransky at the Rado Buransky’s Blog blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of