Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.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
Scala:理解匿名函数语法_Scala_Anonymous Function - Fatal编程技术网

Scala:理解匿名函数语法

Scala:理解匿名函数语法,scala,anonymous-function,Scala,Anonymous Function,我试图理解另一个程序员编写的Scala中的自定义迭代器。 我很难理解函数声明。 对我来说,它们看起来像匿名函数,但我无法完全理解它们 我阅读了一些Scala中的匿名函数,我发现这个资源非常有用,但我仍然无法阅读上面的函数并完全理解它们 代码如下: class MyCustomIterator(somePath: Path, someInt: Int, aMaxNumber: Int) { def customFilter:(Path) => Boolean = (p) =>

我试图理解另一个程序员编写的Scala中的自定义迭代器。 我很难理解函数声明。 对我来说,它们看起来像匿名函数,但我无法完全理解它们

我阅读了一些Scala中的匿名函数,我发现这个资源非常有用,但我仍然无法阅读上面的函数并完全理解它们

代码如下:

class MyCustomIterator(somePath: Path, someInt: Int, aMaxNumber: Int) {
      def customFilter:(Path) => Boolean = (p) => true
       // Path is from java.nio.files.Path
      def doSomethingWithPath:(Path) => Path = (p) => p
}
我想了解这些函数。返回类型到底是什么?函数的主体是什么

.

(对于第一个
def
)冒号后面和等号前面的部分是返回类型。因此,返回类型为:

Path => Boolean
表示函数签名

现在,分解一下,箭头左边的项目是函数的参数,右边是函数的返回类型

因此,它返回的函数接受
路径
并返回
布尔值
。在这种情况下,它返回的函数将接受
路径
,并返回
真值

第二个
def
返回一个函数,该函数接受一个
路径
,并返回另一个
路径
(在本例中为相同的
路径

示例用法如下所示:

第一种方法: 或

第二种方法: 或


可以添加,更常见的是查看
def customFilter:Path=>Boolean=\true
def doSomethingWithPath:Path=>Path=identity
。这更容易阅读吗?贾斯汀,我喜欢你的解释。不过,让我完全正确地理解:“箭头左侧的项是函数的参数。”-是吗“Boolean=(p)=>true”如果是这样,我们如何解释这个语法。@som snytt,这更容易阅读。Path是返回类型,这个东西是“Boolean=\uyt=>true”“是返回类型吗?下划线是什么?我觉得它像一个占位符。你说的:Path=identity是什么意思?我不能得到identity部分。@user3825558,我认为这样更清楚:
def customFilter:Boolean)=(\code>或
def customFilter:Boolean)=((p)=>true)
。这些与原始代码中的完全相同。现在括号清楚地界定了类型和表达式,您可以看到
customFilter
是一个返回函数的方法。
iter.customFilter(myPath) //returns true
val pathFunction = iter.customFilter;
pathFunction(myPath) //returns true
iter.doSomethingWithPath(myPath) //returns myPath
val pathFunction = iter.doSomethingWithPath
pathFunction(myPath) //returns myPath