Sen*_*ess 26 scala function partial-application
我注意到当我使用期望其他函数作为参数的函数时,我有时可以这样做:
someFunction(firstParam,anotherFunction)
Run Code Online (Sandbox Code Playgroud)
但其他时候,编译器给我一个错误,告诉我应该编写一个这样的函数,以便将它视为部分应用的函数:
someFunction(firstParam,anotherFunction _)
Run Code Online (Sandbox Code Playgroud)
例如,如果我有这个:
object Whatever {
def meth1(params:Array[Int]) = ...
def meth2(params:Array[Int]) = ...
}
import Whatever._
val callbacks = Array(meth1 _,meth2 _)
Run Code Online (Sandbox Code Playgroud)
为什么我不能拥有如下代码:
val callbacks = Array(meth1,meth2)
Run Code Online (Sandbox Code Playgroud)
在什么情况下编译器会告诉我添加_?
Jea*_*let 27
规则实际上很简单:_只要编译器没有明确地期望Function对象,就必须编写规则.
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>
Run Code Online (Sandbox Code Playgroud)
在Scala中,方法不是函数.编译器可以在函数中隐式转换方法,但需要知道哪种方法.因此,要么您使用_显式转换它,要么您可以给出一些关于使用哪种函数类型的指示:
object Whatever {
def meth1(params:Array[Int]): Int = ...
def meth2(params:Array[Int]): Int = ...
}
import Whatever._
val callbacks = Array[ Array[Int] => Int ]( meth1, meth2 )
Run Code Online (Sandbox Code Playgroud)
要么:
val callbacks: Array[ Array[Int] => Int ] = Array( meth1, meth2 )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11021 次 |
| 最近记录: |