Is there a way in scala to get the arguments back from a already partially applied function?
Does this even make sense, should be done, or fits into any use case?
example:
def doStuff(lower:Int,upper:Int,b:String)=
for(turn <- lower to upper) println(turn +": "+b)
Imagine that at one point I know the ‘lower’ argument and I get a function of applying it to ‘doStuff’
val lowerDoStuff = doStuff(3,_:Int,_:String)
Is there a way for me to get that 3 back ?
(for the sake of example, imagine that I am inside a function which only received ‘lowerDoStuff’ and now needs to know the first argument)
Idiomatic scala is prefered to introspection/reflection (if possible).
Idiomatic Scala: no, you can’t. You have specifically said that the first argument is no longer relevant. If the compiler can make it disappear entirely, that’s best: you say you have a function that depends on an int and a string, and you haven’t made any promises about what generated it. If you really need that value, but you also really need to pass a 2-argument function, you can do it by hand:
Now when you get the function later on, you can pattern match to see if it’s a Function2From3, and then read the value:
(if it’s important to you that it be an integer, you can remove
Aas a generic parameter and make_1be an integer–and maybe just call itlowerwhile you’re at it).Reflection: no, you can’t (not in general). The compiler’s smarter than that. The generated bytecode (if we wrap your code in
class FuncApp) is:Notice the
iconst_3? That’s where your 3 went–it disappeared into the bytecode. There’s not even a hidden private field containing the value any more.