Passing a function as a parameter, why the => symbol is required in my scenerio?

Viewed 85
case class User(id: Int)
def Transform(u: User): String = u.id.toString()

def Process[A](f: A => String): String = "hello"

val u = User(123)
println(Process(u => Transform(u)))   // Scenerio#1 works fine

println(Process(Transform(u)))        // error
println(Process[User](Transform(u)))  // error

I'm a little confused as to why I need the => in Scenerio#1

I have a function Process that takes a function. The function requires:

  1. a parameter of type A
  2. return value of String.

Now I have a function named Transform that takes a parameter of type A (a User) and returns a string.

Why can't I pass in:

Process(Transform(u)) 

I am passing it a function that meets the requirements am I not? (I guess not but I don't understand!)

I guess I still don't understand what the following notation really means:

Process(u => Transform(u))
2 Answers

As you already noticed, Transform is of type User => String, therefore, you can just pass it as a parameter to Process:

val process1: String = Process(u => Transform(u))
val process2: String = Process(Transform)
val process3: String = Process[User](Transform)

All of the above are exactly the same, and outputs hello.

def Process[A](f: A => String) method in your code is expecting a function definition as argument whose input parameter type should A and return type should be String.

Case 1: println(Process(u => Transform(u)))

You are passing function definition so it is working fine as per expectation.

Case 2: println(Process(Transform(u))) // error println(ProcessUser) // error

You are not passing function definition here as expected by Process function instead you are passing the function call Transform(u) which will return the value and pass as argument to Process function.

You can refer high order function in scala using this link (https://docs.scala-lang.org/tour/higher-order-functions.html).

Related