首页 > 解决方案 > 如何在scala中为flatMap定义一个函数

问题描述

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 = 列表[任何]

这个功能有什么问题?而对于flatMap,它是一种将结果作为列表返回的写入方式吗?

标签: scalaapache-spark-sql

解决方案


您还没有解释为什么要替换该代码块。你有一个特定的目标吗?有很多很多不同的方式可以重写块。我们如何知道哪个更能满足您的要求?

这是一种方法。

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

推荐阅读