Scala委托在多参数方法调用中

时间:2013-09-24 16:30:47

标签: scala delegates

假设有一个名为“delegatedFoo()”的函数委托方法需要作为参数传递给方法(即scala的函数指针版本),如下所示:

addMyDelegatedMethod(delegatedFoo)

假设(为简洁起见),该行编译/执行就好了。现在改为:

addMyDelegateOverrideMethod("uh-o", delegatedFoo)

此行将抛出编译器异常:类myClass中的方法delegatedFoo缺少参数

问:如何在多参数方法调用中传递委托(引用)? (这是甚至可以在Scala中完成的吗?)

编辑:更准确地说,签名如下:

def delegatedFoo(str: String): String = { return "OK" }
def addMyDelegatedMethod(delegate: (String) => (String))
def addMyDelegateOverrideMethod(foo: String, delegate: (String) => (String))

更新:在审核了Paolo的答案并进行了一些更多的实验之后,我可以告诉问题(错误?)表面,当涉及到超载的签名时。 (我没有把它扔到上面的例子中,因为它没有被使用 - 但只是它似乎让我的编译器头痛):

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 for method myFn;
follow this method with `_' if you want to treat it as a partially applied function
          MyControl.doDele("hello", "bye", myFn)

MyControl定义了一组重载方法...注释掉重载方法(或更改其名称),编译器将处理它......:\

1 个答案:

答案 0 :(得分:1)

更新:

如错误所示,您需要明确跟随myFn _

scala> MyControl.doDele("hello", "bye", myFn _)
hello

原因在于scala中的方法(您使用def定义并存在于类或对象中的方法)不是函数(实际上更像是具有apply的对象它自己的方法)。在某些情况下,您可以传递一个需要函数的方法,并且scala会将一个“转换”为另一个。但是,一般情况下,您必须使用_的方法来告诉scala将其视为函数。

请注意,例如,在定义后的REPL中:

scala> myFn
<console>:9: error: missing arguments for method myFn;
follow this method with `_' if you want to treat it as a partially applied funct
ion
              myFn
              ^

scala> myFn _
res4: String => String = <function1>

__

也许你应该提供一个更完整的例子来说明你要做什么/失败了什么,但这在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
相关问题