Back2Basics: Pass-By-Name and HOF in Scala argue as a Husband And Wife.

Scala has lots of features and one of the features always confused me called “pass-by-name” argument.  For me pass by name is same as “higher-order-function” but different from just syntax otherwise everything is same. While googling out for their difference, I found:

  1. Pass-by-name is lazy evaluation but higher-order-functions are eager.
  2. Pass-by-name is used for constructs custom controls.

and maybe there are more, but these two are available everywhere. Every time, I read about its different but always have one doubt Why pass-by-name is required ???

Mustaches-Baby-Crying-Sad-Face-Funny-Image

Finally, I found my answer and the main differences, which satisfy my internal soul and clear all doubts about “pass-by-name” and “higher-order-function“.

pass-by-name

With some findings, the conclusion is like “pass-by-name” act as a husband but “higher-order-functions” act as a wife. How??

We are sure, wifes are always happy and believed in arguments but husbands are like innocent creature which accepts every argument and always evaluate lazily when someone tells. The same theory is implemented in Scala.

2-300x168

In scala, “higher-order-functions” are same as wife, while we declaring “higher-order-function” as an argument, it only works if passed parameter type and a count is match but “pass-by-name” is like of innocent husband which accepts any type of arguments and any number of arguments and only evaluate if someone ask otherwise nothing can do. Let’s take a Scala example:

  • The example contains four methods with the different number of arguments and different type of arguments “method(x)“.
  • While we need to pass “method(x)” as a “higher-order-functions“, we require to create different methods according to passed arguments, so we have three “hofArg(x)” methods. 
  • But in the case of “pass by name” argument, we are creating only one method which takes an argument as “pass-by-name” and method called “byNameArg“. 
  • While calling this method with different types and number of arguments, the method executes successfully and prints its results.

After this huge different now I am pretty much sure, when we need to use “pass by name” and when to use “higher-order-function“.


knoldus-advt-sticker


 

Written by 

Harmeet Singh is a lead consultant, with experience of more than 5 years. He is #programmer #geek #scala #java #jvm #functional #back2basics #foodlover #family http://www.harmeetsingh.in/

2 thoughts on “Back2Basics: Pass-By-Name and HOF in Scala argue as a Husband And Wife.

Leave a Reply

%d bloggers like this: