scala - 如何在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,它是一种将结果作为列表返回的写入方式吗?
解决方案
您还没有解释为什么要替换该代码块。你有一个特定的目标吗?有很多很多不同的方式可以重写块。我们如何知道哪个更能满足您的要求?
这是一种方法。
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)
}
}
推荐阅读
- css - 如何解决 Angular 12 中的 CSS 模块错误
- laravel - 由于目标机器主动拒绝,无法建立连接。[tcp://127.0.0.1:6037]
- javascript - 如何比较不同数组中不同对象之间的对象属性
- javascript - 如何在 React 中映射另一个文件中的对象数组?
- python - 如何在json文件中获取key的值数据
- windows - 写入另一个程序正在使用的文件
- html - 没有在子域中点击 index.html。我得到 / 的索引,但列出了 cgi-bin 文件夹
- javascript - 如何从重新连接的 create-react-app 条目中的 node_modules 导入命名空间 css?react-app-rewire-multiple-entry 是要走的路吗?
- javascript - 'searchList' 被分配了一个值,但从未使用过 no-unused-vars
- java - Gradle 同步失败,找不到 com.android.tools.build:gradle:7.2