考虑以下代码:
object HelloIntelliScala {
def main(args : Array[String]) = {
println(callAnyFunc(funcWithNoArgs))
val l = callAnyFuncWithArgs("bingo") (funcWithArgs)
println(l)
val l2 = callAnyFuncWithArgs(21) (funcWithArgs2)
println(l2)
}
type noArgCallBack = () => Any
def funcWithArgs(inp : String) : Any = {
println("Func with arg called, arg value is: " + inp)
"Hello " + inp + "!"
}
def funcWithArgs2(inp : Int) : Any = {
println("Func with arg called, arg value is: " + inp)
"Hello, integer " + inp + "!"
}
//how do i call this function?
def funcWithArgs3(inp : Int, name : String) : Any = {
println("Func with 2 args called, arg values are: " + (inp, name))
"Hello, multiple args " + (inp, name) + "!"
}
def funcWithNoArgs() : Any = {
println("Function with no args was called!")
"Hello NO_ARGS"
}
def callAnyFunc(callback : noArgCallBack) : Any = {
callback();
}
def callAnyFuncWithArgs[A, B](arg : A)(f : A => B) : Any = {
f(arg); //how do I pass variable args here
}
}
我需要一种通用的方法来调用任何带参数的函数,就像没有参数的函数一样。请注意,要传入的参数列表可以是可变的,我们在编译时不知道参数类型。此外,我确实需要 Any 返回类型,因为我需要将此值用于后期处理。有没有办法做到这一点?