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

后端 未结 2 2048
生来不讨喜
生来不讨喜 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:34

    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
    }
    

提交回复
热议问题