我什么时候需要将我的方法作为Scala中的部分应用函数处理? [英] When do I have to treat my methods as partially applied functions in Scala?

查看:136
本文介绍了我什么时候需要将我的方法作为Scala中的部分应用函数处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  someFunction(firstParam,anotherFunction)

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

  someFunction(firstParam,anotherFunction _)

例如,如果我有这样的话:

  object无论如何{
def meth1(params:Array [Int])= ...
def meth2(params:Array [Int])=。 ..
}

import Whatever._
val callbacks = Array(meth1 _,meth2 _)

为什么我不能拥有类似以下的代码:

  val callbacks = Array(meth1,meth2)

在编译器要求我添加 _

_ ,就必须编写 _ c $ c> Function object。



REPL中的示例:

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

scala> val g = f
< console>:6:错误:缺少对象$ iw中方法f的参数;
如果您想将其视为部分应用函数,则使用`_'遵循此方法
val g = f
^

scala> val g:Int => Int = f
g:(Int)=> Int =< function1>


I noticed that when I'm working with functions that expect other functions as parameters, I can sometimes do this:

someFunction(firstParam,anotherFunction)

But other times, the compiler is giving me an error, telling me that I should write a function like this, in order for it to treat it as a partially applied function:

someFunction(firstParam,anotherFunction _)

For example, if I have this:

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

import Whatever._
val callbacks = Array(meth1 _,meth2 _)

Why can't I have the code like the following:

val callbacks = Array(meth1,meth2)

Under what circumstances will the compiler tell me to add _?

解决方案

The rule is actually simple: you have to write the _ whenever the compiler is not explicitly expecting a Function object.

Example in the 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中的部分应用函数处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆