如何在 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,它是将结果作为List返回的写入方式吗?

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

这里有一种方法。

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

最新更新