【问题标题】:How to define a function in scala for flatMap如何在scala中为flatMap定义一个函数
【发布时间】:2019-03-19 08:37:12
【问题描述】:

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返回的写法?

【问题讨论】:

  • 我不确定你试图通过反复添加到单个元素 tempList 来实现什么?无论错误消息如何,它似乎都不太正确。也不太清楚“用户定义的函数”是什么意思——只有你的方法,没有udfs?
  • 您好,感谢您的回复。我对火花和斯卡拉世界很陌生。所以,如果我写了任何不清楚的地方,请多多包涵。我的意图是用一个函数替换 flatMap 中的长代码。但显然我写的函数有编译问题,我不确定哪个部分出错了。我的第二个问题是我应该如何用函数替换原始代码。 flatMap 是否传入 Row 对象,返回类型预计为元组列表?

标签: scala apache-spark-sql


【解决方案1】:

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

这是一种方法。

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

【讨论】:

  • 谢谢jwvh。我正在学习Scala和Spark,所以我想替换代码的原因纯粹是为了学习和好奇。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2020-08-17
  • 2020-07-22
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多