Yet another developer. Java, C#, C++. Aiming for Scala. Rado is a DZone MVB and is not an employee of DZone and has posted 12 posts at DZone. You can read more from them at their website. View Full User Profile

Scala Wonderland: The Functional Style

07.17.2013
| 3455 views |
  • submit to reddit

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) {
    println(args(i))
    i += 1
  }
}

More functional style:

def printArgs(args: Array[String]): Unit = {
  args.foreach(println)
}

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 isUnit. 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")
println(formatArgs(args))

Prefer vals, immutable objects and methods without side effects.

Published at DZone with permission of Rado Buranský, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)