首页 > 解决方案 > 用于转换 spark 数据框列的通用函数

问题描述

我编写了以下函数,它转换了 spark 数据框列,但我想让它使用类型化函数:

def castCol(newName: String, previosuNmae: String, datatType: DataType): DataFrame = {
  df.withColumn(newName, col(previosuNmae).cast(datatType))

我宁愿让它像:

def castCol[DataType](newName: String, previosuNmae: String): DataFrame = {
  df.withColumn(newName, col(previosuNmae).cast(DataType)) 

但这不起作用。你知道谁将 dataType 作为类型而不是参数传递给函数吗

标签: scalaapache-sparktypeclass

解决方案


这个怎么样:

def castCol[T<:DataType](newColName: String, newColType:T, previousColName: String): DataFrame = 
    df.withColumn(newColName, col(previousColName).cast(newColType))

希望能帮助到你


推荐阅读