Scala 方法内部的匿名函数
Anonymous function inside a method in Scala
我正在查看示例代码之一(如下所示)。我注意到在这个方法中定义了一个匿名函数(下面一行//代码片段中的这个注释是什么)。这到底是什么以及如何调用它?
def initHasher(requestFilePath: String) = {
import spark.implicits._
val hashes = spark.read.option("delimiter", ",").option("header", "true").csv(requestFilePath)
.select($"Hash", $"Count").rdd
.map(r => (r.getString(0), r.getString(1))).collectAsMap()
val broadcastedHashes = spark.sparkContext.broadcast(hashes)
// What is this?
(str: String) => {
if (str != null && str.length > 0) {
val hash = sha256hash(str)
broadcastedHashes.value.get(hash) match {
case None => hash
case Some(count) => sha256hash(str + ":" + count)
}
}
else
null
}
}
initHasher
初始化一个散列器并 returns 它作为一个函数(你看到的匿名函数)。它会像这样使用:
// initialize your hasher here
val hasher = initHasher(requestFilePath)
// now you can use the hasher
val hash = hasher("my string")
我正在查看示例代码之一(如下所示)。我注意到在这个方法中定义了一个匿名函数(下面一行//代码片段中的这个注释是什么)。这到底是什么以及如何调用它?
def initHasher(requestFilePath: String) = {
import spark.implicits._
val hashes = spark.read.option("delimiter", ",").option("header", "true").csv(requestFilePath)
.select($"Hash", $"Count").rdd
.map(r => (r.getString(0), r.getString(1))).collectAsMap()
val broadcastedHashes = spark.sparkContext.broadcast(hashes)
// What is this?
(str: String) => {
if (str != null && str.length > 0) {
val hash = sha256hash(str)
broadcastedHashes.value.get(hash) match {
case None => hash
case Some(count) => sha256hash(str + ":" + count)
}
}
else
null
}
}
initHasher
初始化一个散列器并 returns 它作为一个函数(你看到的匿名函数)。它会像这样使用:
// initialize your hasher here
val hasher = initHasher(requestFilePath)
// now you can use the hasher
val hash = hasher("my string")