Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function 什么时候我必须在Scala中将我的方法视为部分应用的函数?_Function_Scala_Partial Application - Fatal编程技术网

Function 什么时候我必须在Scala中将我的方法视为部分应用的函数?

Function 什么时候我必须在Scala中将我的方法视为部分应用的函数?,function,scala,partial-application,Function,Scala,Partial Application,我注意到,当我使用期望其他函数作为参数的函数时,有时我可以这样做: someFunction(firstParam,anotherFunction) 但其他时候,编译器会给我一个错误,告诉我应该编写一个这样的函数,以便将其视为部分应用的函数: someFunction(firstParam,anotherFunction _) 例如,如果我有: object Whatever { def meth1(params:Array[Int]) = ... def meth2(par

我注意到,当我使用期望其他函数作为参数的函数时,有时我可以这样做:

someFunction(firstParam,anotherFunction)
但其他时候,编译器会给我一个错误,告诉我应该编写一个这样的函数,以便将其视为部分应用的函数:

someFunction(firstParam,anotherFunction _)
例如,如果我有:

object Whatever {
    def meth1(params:Array[Int]) = ...
    def meth2(params:Array[Int]) = ...
}

import Whatever._
val callbacks = Array(meth1 _,meth2 _)
为什么我不能有如下代码:

val callbacks = Array(meth1,meth2)

在什么情况下,编译器会告诉我添加
\u

规则实际上很简单:只要编译器没有明确地期望
函数
对象,就必须编写
\u

REPL中的示例:

scala> def f(i: Int) = i    
f: (i: Int)Int

scala> val g = f
<console>:6: error: missing arguments for method f in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       val g = f
               ^

scala> val g: Int => Int = f  
g: (Int) => Int = <function1>
scala>def(i:Int)=i
f:(i:Int)Int
scala>val g=f
:6:错误:对象$iw中缺少方法f的参数;
如果要将其视为部分应用的函数,请使用“\u1”遵循此方法
val g=f
^
scala>val g:Int=>Int=f
g:(Int)=>Int=

除了Jean-Philippe Pellet所说的,在编写委托类时,还可以使用部分应用的函数:

class ThirdPartyAPI{
   def f(a: Int, b: String, c: Int) = ...
   // lots of other methods
}

// You want to hide all the unnecessary methods
class APIWrapper(r: ThirdPartyAPI) {
   // instead of writing this
   def f(a: Int, b: String, c: Int) = r.f(a, b, c)
   // you can write this
   def f(a: Int, b: String, c: Int) = r.f _
   // or even this
   def f = r.f _
}

EDIT添加了
def=r.f
部分。

在Scala中,方法不是一个函数。编译器可以在函数中隐式转换方法,但需要知道是哪种方法。因此,您可以使用
\uu
显式转换它,也可以给出一些关于要使用哪种函数类型的指示:

object Whatever {
  def meth1(params:Array[Int]): Int = ...
  def meth2(params:Array[Int]): Int = ...
}

import Whatever._
val callbacks = Array[ Array[Int] => Int ]( meth1, meth2 )
或:


请注意,它不是一个部分函数,而是一个部分应用的函数。不应该(r:RichAPI)是(r:ThnirdPartyAPI)吗?“//youcan write this part”不应该是:def f=r.f吗?这就创建了f:(a:Int,b:String,c:Int)(Int,String,Int)=>…我认为只有函数才有可能,而不是方法。很高兴知道,谢谢。我会加上它的权利away@JaimeJorge@agilesteel情况不同
f
现在变成了一个没有参数列表的方法,该参数列表返回类型为
(Int,String,Int)=>a的函数。这里有一些开销。另请参见。
val callbacks: Array[ Array[Int] => Int ] = Array( meth1, meth2 )