Scala delegate within multi-argument method call -
assume there functional delegate method called "delegatedfoo()" needs passed argument method (ie, scala's version of function pointer) so:
addmydelegatedmethod(delegatedfoo)
assume (for brevity), line compiles/executes fine. change this:
addmydelegateoverridemethod("uh-o", delegatedfoo)
this line throw compiler exception: missing arguments method delegatedfoo in class myclass
q: how 1 go passing delegate (reference) within multi-argument method call? (is can done in scala?)
edit: more precise, signatures follows:
def delegatedfoo(str: string): string = { return "ok" } def addmydelegatedmethod(delegate: (string) => (string)) def addmydelegateoverridemethod(foo: string, delegate: (string) => (string))
update: after reviewing paolo's answer , doing more experimenting, best can tell issue (bug?) surfaces when there overloaded signature involved. (i didn't bother throwing example above, wasn't used -- having there appears give compiler headache):
scala> object mycontrol { def dodele(stra: string, strb: string, delegate: string => string) { delegate(stra) } def dodele(stra: string, count: int, delegate: string => string) { delegate(stra) } } defined module mycontrol scala> def myfn(s: string): string = { println(s); s } myfn: (s: string)string scala> mycontrol.dodele("hello", "bye", myfn) <console>:10: error: missing arguments method myfn; follow method `_' if want treat partially applied function mycontrol.dodele("hello", "bye", myfn)
mycontrol has set of overloaded methods defined...comment out overload method (or change name) , compiler handle fine... :\
update:
as error says need explicitly follow myfn
_
scala> mycontrol.dodele("hello", "bye", myfn _) hello
the reason in scala method (what define def
, lives in class or object) not function (which more object apply
method of own). in cases can pass method function required , scala "transform" 1 other you. in general, though, have follow method _
tell scala treat function.
note this, instance, in repl after definitions:
scala> myfn <console>:9: error: missing arguments method myfn; follow method `_' if want treat partially applied funct ion myfn ^ scala> myfn _ res4: string => string = <function1>
__
maybe should provide more complete example of you're trying do/what fails, works fine in scala:
scala> def delegatedfoo(str: string): string = "ok" delegatedfoo: (str: string)string scala> def addmydelegatedmethod(delegate: string => string) = delegate("meh") addmydelegatedmethod: (delegate: string => string)string scala> def addmydelegateoverridemethod(foo: string, delegate: string => string) = delegate(foo) addmydelegateoverridemethod: (foo: string, delegate: string => string)string scala> addmydelegatedmethod(delegatedfoo) res0: string = ok scala> addmydelegateoverridemethod("hey",delegatedfoo) res4: string = ok
Comments
Post a Comment