Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I take any function as input for my Scala wrapper method?

Let's say I want to make a little wrapper along the lines of:

def wrapper(f: (Any) => Any): Any = {
  println("Executing now")
  val res = f
  println("Execution finished")
  res
}

wrapper {
  println("2")
}

Does this make sense? My wrapper method is obviously wrong, but I think the spirit of what I want to do is possible. Am I right in thinking so? If so, what's the solution? Thanks!

like image 580
pr1001 Avatar asked Apr 17 '10 09:04

pr1001


People also ask

What is the meaning of => in scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What do you call a function defined in a block in scala?

A method is a function defined in a class and available from any instance of the class. The standard way to invoke methods in Scala (as in Java and Ruby) is with infix dot notation, where the method name is prefixed by the name of its instance and the dot ( . )

What is a higher order function in scala takes other functions as input parameters returns a function as a result all of the above None of these?

A higher-order function (HOF) is often defined as a function that (a) takes other functions as input parameters or (b) returns a function as a result. In Scala, HOFs are possible because functions are first-class values.


2 Answers

If you want your wrapper method to execute the wrapped method inside itself, you should change the parameter to be 'by name'. This uses the syntax => ResultType.

def wrapper(f: => Any): Any = {
  println("Executing now")
  val res = f
  println("Execution finished")
  res
}

You can now do this,

wrapper {
  println("2")
}

and it will print

Executing now
2
Execution finished

If you want to be able to use the return type of the wrapped function, you can make your method generic:

def wrapper[T](f: => T): T = {
  println("Executing now")
  val res: T = f
  println("Execution finished")
  res
}
like image 78
Ben Lings Avatar answered Sep 29 '22 21:09

Ben Lings


In your case you are already executing the function println and then pass the result to your wrapper while it is expecting a function with one arguments (Any) and that return Any.

Not sure if this answer to your question but you can use a generic type parameter and accept a function with no arguments that return that type:

def wrapper[T](f: () => T) = {
  println("Executing now")
  val res = f() // call the function
  println("Execution finished")
  res
}

wrapper {
  ()=>println("2") // create an anonymous function that will be called
}
like image 29
Patrick Avatar answered Sep 29 '22 21:09

Patrick