gpt4 book ai didi

Scala:理解匿名函数语法

转载 作者:行者123 更新时间:2023-12-01 22:39:42 24 4
gpt4 key购买 nike

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

我阅读了一些有关 Scala 中的匿名函数的内容,并找到了此资源 [ http://www.scala-lang.org/old/node/133]有帮助,但我仍然无法阅读上述函数并完全理解它们。

这是代码:

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

表示函数签名。

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

因此,它返回一个接受 Path 并返回 Boolean 的函数。在本例中,它返回一个函数,该函数将接受 Path 并返回 true 无论如何。

第二个 def 返回一个接受 Path 并返回另一个 Path 的函数(与本例)

一个示例用法是按如下方式使用它们:

第一种方法:

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

关于Scala:理解匿名函数语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29335789/

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