【问题标题】:Anonymous function inside a method in ScalaScala中方法内的匿名函数
【发布时间】:2017-11-08 02:45:54
【问题描述】:

我正在查看其中一个示例代码(如下所示)。我注意到这个方法中定义的看起来像一个匿名函数(下面的行//sn-p 中的这个注释是什么)。这到底是什么以及如何调用它?

 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
      }
    }

【问题讨论】:

    标签: scala apache-spark anonymous-function


    【解决方案1】:

    initHasher 初始化一个散列器并将其作为函数返回(您所看到的匿名函数)。它会这样使用:

    // initialize your hasher here
    val hasher = initHasher(requestFilePath)
    
    // now you can use the hasher
    val hash = hasher("my string")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多