Scala – Pass function as a parameter
In Scala, we can pass a function as a parameter to another function or say method. For that we have to follow the below guidelines.
- Define your method , including the function signature that it will accepts as a parameter.
- Define the function with the exact signature that will be passed a method parameter.
- Pass the function as a parameter to the methosd.
Let’s understand this with an example.A method named EmpDetails has been defined which accepts another function yearlySalary as its parameter which has same function signature.
object FuncAsParam { def main(args: Array[String]): Unit = { EmpDetails("Tom",30000,yearlySalary) } def EmpDetails(name:String,salary:Int, f:Int=>Int)= { print(name +"'s salary per anum in INR - "+ f(salary) ) } def yearlySalary(sal:Int): Int ={ sal * 12 } }
Output:
Tom's salary per anum in INR - 360000