Scala序数方法调用别名

Nig*_*olf 2 functional-programming scala implicit apache-spark

在Spark SQL中,我们有Row对象,其中包含组成一行的记录列表(想想Seq[Any]).A Row有序数访问器,如.getInt(0)getString(2).

假设序号0 = ID且序数1 =名称.很难记住顺序是什么,使代码混乱.

比方说,我有以下代码

def doStuff(row: Row) = {
  //extract some items from the row into a tuple;
  (row.getInt(0), row.getString(1)) //tuple of ID, Name
}
Run Code Online (Sandbox Code Playgroud)

问题是如何在Row对象中为这些字段创建别名?

我在想我可以创建一个隐含Row对象的方法;

def id(implicit row: Row) = row.getInt(0)
def name(implicit row: Row) = row.getString(1)
Run Code Online (Sandbox Code Playgroud)

然后我可以重写上面的内容;

def doStuff(implicit row: Row) = {
  //extract some items from the row into a tuple;
  (id, name) //tuple of ID, Name
}
Run Code Online (Sandbox Code Playgroud)

有更好/更整洁的方法吗?

maa*_*asg 5

您可以隐式地将这些访问器方法添加到行:

implicit class AppRow(r:Row) extends AnyVal {
    def id:String = r.getInt(0)
    def name:String = r.getString(1)
}
Run Code Online (Sandbox Code Playgroud)

然后用它作为:

def doStuff(row: Row) = {
  val value = (row.id, row.name)
}
Run Code Online (Sandbox Code Playgroud)