Reputation: 6884
i'm writing some scala code to emulate a python decorator. i'm considering implementing this by having the decorator extend a Function trait. the issue is that i want this decorator to extend a Function that accepts any number of arguments, and the only Function traits i can find only allow a specific number of arguments, e.g. Function1, Function2, etc.
does such a trait exist? alternatively, is there a better way to implement such a decorator?
Edit: I recast this question to be more clear at scala: memoize a function no matter how many arguments the function takes?.
Upvotes: 4
Views: 1272
Reputation: 9468
There is not a function supertrait. You will have to wrap the method you want to decorate into an own class with an implicit. That class gonna have to handle the different method types. Then you have to create some class what generates your decorated method.
Or if you can you just create new methods like that:
def myF(x:Int,y:Int)={x*y}
def myF2(x:Int,y:Int)={myDecorator(myF(x,y))}
def myDecorator[X](f:=>X)={println("entering");val ret=f();println("exiting");ret}
or try:
def myF_old(x:Int,y:Int)=x*y
def paramDecorator(x:Any*):List[Any]={/*do some match operations or something*/}
def outputDecorator(x:Any*):Any={/*do some match operations or so*/}
def myF(x:Int,y:Int):Int={
params=paramDecorator(x,y);
val res=myF_old(params(1),params(2));
outputDecorator(res);
}
Upvotes: 0
Reputation: 29143
scala> val bar: (Int*) => Int = {args => args.sum}
bar: (Int*) => Int = <function1>
scala> bar(1,2,3)
res4: Int = 6
Unfortunatelly, you can't use type inference here:
scala> val bar = {args: Int* => args.sum}
<console>:1: error: ';' expected but identifier found.
val bar = {args: Int* => args.sum}
Upvotes: 2
Reputation: 54584
I'm not sure what you try to accomplish, but if you have problems with the arity of functions, you can work on a Function1 which uses a Tuple as input parameter. As it is easy to convert between tupled and untuples versions for any function, this should be not too inconvenient. I could give you a code example if you would describe more detailed what you need.
Upvotes: 0