Turn method into a Function in Scala
In Scala you have both methods and functions. A function is kind of a value which can be passed around. At times you might need to pass a something which is defined as a method but you can’t pass a method just like functions.
Scala provides an easy way to do so. Let’s take an example of sum of two numbers.
def sum(a: Int, b: Int): Int = a + b
To make that as a function you can do as follows
val sumFn = sum _
This will provide you with a value that can be passed around and you can execute it as a normal function.
The above method works differently for a variable argument method for example lets take a combine method definition as follows.
def combine(args: String*): String = args.mkString(“|”)val combineFn = combine _
Here you will get a function of the signature as below
Seq[String] => String
This is not a hack as such, it turns a method into a function that delegates to the method. But along the way it performs a lot of simplifications, including turning vararg parameters into Seq parameters.