gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:30:17 26 4
gpt4 key购买 nike

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

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)

什么情况下编译器会告诉我添加_

最佳答案

规则实际上很简单:只要编译器未明确期望 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>

关于function - 我什么时候必须将我的方法视为 Scala 中的部分应用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6650989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com