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

别说谁变了你拦得住时间么 提交于 2019-12-05 16:46:45

问题


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!


回答1:


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
}



回答2:


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
}


来源:https://stackoverflow.com/questions/2657940/how-can-i-take-any-function-as-input-for-my-scala-wrapper-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!