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

Prefer vals, immutable objects and methods without side effects.


Leave a Reply