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

Let's say I want to make a small wrapper line by line:

def wrapper(f: (Any) => Any): Any = { println("Executing now") val res = f println("Execution finished") res } wrapper { println("2") } 
It makes 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 that? If so, what is the solution? Thanks!
+7
function methods scala
source share
2 answers

If you want your wrapper method to execute the wrapped method within itself, you must change the "by name" parameter. This uses the syntax => ResultType .

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

Now you can do it,

 wrapper { println("2") } 

and he will print

 Executing now 2 Execution finished 

If you want to use the return type of a wrapped function, you can make your general method:

 def wrapper[T](f: => T): T = { println("Executing now") val res: T = f println("Execution finished") res } 
+21
source share

In your case, you already execute the println function, and then pass the result to your shell, expecting a function with one argument ( Any ) and return Any .

Not sure if this answer is your question, but you can use a parameter of type type and accept a function without arguments returning this 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 } 
+1
source share

All Articles