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

后端 未结 2 2089
生来不讨喜
生来不讨喜 2021-02-20 03:07

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(\"Ex         


        
2条回答
  •  生来不讨喜
    2021-02-20 03:40

    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
    }
    

提交回复
热议问题