如何在scala中为flatMap定义函数

时间:2018-10-14 23:12:27

标签: scala apache-spark-sql

Scala的新手,我想尝试通过调用一个函数而不是在“()”中编写整个过程来重写flatMap中的一些代码。

原始代码如下:

val longForm = summary.flatMap(row => {
   /*This is the code I want to replace with a function*/
   val metric = row.getString(0)
   (1 until row.size).map{i=>
     (metric,schema(i).name,row.getString(i).toDouble)
    })
}/*End of function*/)

我写的函数是:

def tfunc(line:Row):List[Any] ={
     val metric = line.getString(0)
     var res = List[Any] 
     for (i<- 1 to line.size){
       /*Save each iteration result as a List[tuple], then append to the res List.*/
      val tup = (metric,schema(i).name,line.getString(i).toDouble)
      val tempList = List(tup)
      res = res :: tempList
      }
     res
    }

该函数未通过编译,并出现以下错误:

错误:对象列表中应用的方法缺少参数列表 仅当需要函数类型时,才会将未应用的方法转换为函数。 您可以通过编写apply _apply(_)而不是apply来明确表示此转换。        var res = List [Any]

此功能有什么问题? 对于flatMap,将结果作为List返回是一种写方法吗?

1 个答案:

答案 0 :(得分:0)

您尚未解释为什么要替换该代码块。您追求一个特定的目标吗?有很多很多不同的方式可以重写该块。我们怎么知道哪种会更好地满足您的要求?

这是一种方法。

def tfunc(line :Row) :List[(String,String,Double)] ={
  val metric = line.getString(0)
  List.tabulate(line.tail.length){ idx =>
    (metric, schema(idx+1).name, line.getString(idx+1).toDouble)
  }
}