Scala Question

Functional Programming Principles

So, I am new to functional programming and I am still trying to digest the fundamental principles. So far, I can appreciate that one should ideally code without mutable variables, assignments, loops and other imperative control structures. So I have a question. Between the following two code snipets:

def enrich(xRDD: RDD[xObject], yRDD: RDD[yObject], zRDD: RDD[zObject]): RDD[Result] = {

val temp = functionA(xRDD, yRDD)
functionB(temp, zRDD)


def enrich(xRDD: RDD[xObject], yRDD: RDD[yObject], zRDD: RDD[zObject]): RDD[Result] = {
functionB(functionA(xRDD, yRDD), zRDD)

which one shold I opt for and why? My guess is the second one since it avoids assigning data locally to a temporary val. Is this all there is to it? Did I get it right? Am I missing something?

Answer Source

Both ways are good but depends on usecase which one to go for.

There is nothing wrong about both the ways. You can use any one of the above ways. But as you are not using the value returned by functionA any where except in functionB. Second way looks good (there is no extra variable). Extra variable is less of a concern (memory consumed by reference is insignificant for practical purposes.)


Assignments are OK in functional programming. Reassignments are not OK. Capturing the result using a variable is OK in functional programming. But using var and reassigning the var is not functional programming.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download