0
votes

When learning Scala, I get an example for HIGHER-ORDER FUNCTIONS, from here

https://docs.scala-lang.org/tour/higher-order-functions.html

def apply(f : Int => String, v : Int) = f(v)
def layout[A](x : A) : String = x.toString
println(apply(layout, 1000))

My question is if layout has more than 1 parameters, like this :

def layout[A](x : A, y : A) : String = x.toString + y.toString

for Intuitive understanding, I define apply as follows

def apply(f : Int, Int => String, v : Int, w : Int) = f(v, w)

Of course, this is can not compiled. I think I have a deviation from the understanding of the type of function in Scala.

How to solve this problem with the right posture, and Solve this problem with the right posture, and more in-depth understanding of the definition of scala function types is good.

2
f: (Int, Int) => StringDima

2 Answers

0
votes

Just put a bracket around the arguments

def apply(f : (Int, Int) => String, v1 : Int, v2: Int) = f(v1, v2)

Read about Function traits in scala , there are 22 Function traits are there(Function0, Function1, .....Function2), for your case : http://www.scala-lang.org/api/2.12.3/scala/Function2.html

Also learn about functional interface in Java8 and then try to compare with Scala Function traits.

0
votes

Let me help you with an example

   package scalaLearning

  object higherOrderFunctions {

  def main(args: Array[String]): Unit = {

  def add(a: Int , b:Int):Int =a+b //Function to add integers which two int  values and return and int value
  def mul(a:Int, b:Int ) :Float=a*b //Function which takes two int values and return float value
  def sub(a:Int,b:Int):Int=a-b //function which takes two int values and return int value
  def div(a:Int,b:Int):Float =a/b//Function which takes two int value and return float value

 def operation(function:(Int,Int)=>AnyVal,firstParam:Int,secondParam:Int):AnyVal=function(firstParam,secondParam)   //Higher order function

 println(operation(add,2,4))
 println(operation(mul,2,4))

 println(operation(sub,2,4))
 println(operation(div,2,4))
}
}

Here while creating higher order function which takes input as function,

first you need to understand what type of of inputs your parameter functions takes and what it returns,

In my case it takes two int values and return either float or int so you can mention function_:(Int,Int) => AnyVal

and to pass the parameters to this function you specify firstParam:Int(Thiscould also be firstParam:AnyVal) for the first parameter and specify

secondParam:Int(This could also be secondParam:AnyVal) for second paramter .

   def operation(function(Int,Int)=>AnyVal,firstParam:Int,secondParam:Int):AnyVal=function(firstParam,secondParam)   //Higher order function