Scala 提供代码块作为多个方法参数之一
考虑这些重载的Scala 提供代码块作为多个方法参数之一,scala,Scala,考虑这些重载的groupBy签名: def groupBy[K](f: T => K)(implicit kt: ClassTag[K]): RDD[(K, Iterable[T])] = withScope { groupBy[K](f, defaultPartitioner(this)) } def groupBy[K]( f: T => K, numPartitions: Int)(implicit kt: ClassTag[K])
groupBy
签名:
def groupBy[K](f: T => K)(implicit kt: ClassTag[K]): RDD[(K, Iterable[T])] = withScope {
groupBy[K](f, defaultPartitioner(this))
}
def groupBy[K](
f: T => K,
numPartitions: Int)(implicit kt: ClassTag[K]): RDD[(K, Iterable[T])] = withScope {
groupBy(f, new HashPartitioner(numPartitions))
}
前者的正确/有效调用如下所示:
val groupedRdd = df.rdd.groupBy{ r => r.getString(r.fieldIndex("centroidId"))}
但我无法确定如何添加第二个参数。下面是一个明显的尝试,它给出了语法错误:
val groupedRdd = df.rdd.groupBy{ r => r.getString(r.fieldIndex("centroidId")),
nPartitions}
我也试过(也有语法错误):
顺便说一句,这里有一种方法是有效的。。但是我正在寻找内联语法
def func(r: Row) = r.getString(r.fieldIndex("centroidId"))
val groupedRdd = df.rdd.groupBy( func _, nPartitions)
由于这是一个具有类型参数
T
,K
的通用方法,Scala有时无法从上下文中推断这些类型应该是什么。在这种情况下,您可以通过提供如下类型注释来提供帮助:
df.rdd.groupBy({ r: Row => r.getString(r.fieldIndex("centroidId")) }, nPartitions)
这也是该方法有效的原因:
def func(r: Row) = r.getString(r.fieldIndex("centroidId"))
val groupedRdd = df.rdd.groupBy(func _, nPartitions)
这将
r
的类型固定为行
,类似于上面的方法。这样如何:df.rdd.groupBy({r:Row=>r.get…},nPartitions)
@yǝsʥlA,已经显示为上面的第二个语法错误示例注意类型注释行
好的,我会尝试一下:请回答
def func(r: Row) = r.getString(r.fieldIndex("centroidId"))
val groupedRdd = df.rdd.groupBy(func _, nPartitions)