加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

什么时候在Scala中将我的方法视为部分应用的功能?

发布时间:2020-12-16 09:42:56 所属栏目:安全 来源:网络整理
导读:我注意到,当我使用期望其他函数作为参数的函数时,我有时可以这样做: someFunction(firstParam,anotherFunction) 但是其他时候,编译器给我一个错误,告诉我应该写一个这样的函数,以便它把它当作一个部分应用的函数: someFunction(firstParam,anotherFun
我注意到,当我使用期望其他函数作为参数的函数时,我有时可以这样做:

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读