gpt4 book ai didi

scala - 为什么当我编写 PairDStreamFunctions.reduceByKey 时 scala 编译器无法推断类型

转载 作者:行者123 更新时间:2023-12-02 20:11:35 25 4
gpt4 key购买 nike

我想知道为什么当我使用 PairDStreamFunctions.reduceByKey 时 scala 编译器无法推断出我的函数参数的类型,代码如下:

val ssc = new StreamingContext(conf, Seconds(10))
ssc.checkpoint(".checkpoint")
val lines = ssc.socketTextStream("localhost", 9999)
val words = lines.flatMap(_.split(" "))
val wordCounts = words
.map((_, 1))
.reduceByKey((x: Int, y: Int) => x + y, 4) //here i must specify the type Int,and this format can't work : reduceByKey((x, y) => x + y, 4)

这里我必须指定我的函数参数的类型Int,例如reduceByKey((x: Int, y: Int) => x + y, 4)当我使用 PairDStreamFunctions.reduceByKey ,这种格式无法工作:reduceByKey((x, y) => x + y, 4)

另一方面,当我使用 PairRDDFunctions.reduceByKey api 时,它可以推断类型,代码如下:

val conf = new SparkConf()
val sc = new SparkContext(conf)
val rdd = sc.parallelize(List(
"hi what"
, "show you"
, "matter how"
))
rdd.flatMap(_.split(" "))
.map((_, 1))
.reduceByKey((x, y) => x + y, 4)//in this code,scala compiler could infer the type of my function parameter (x,y) => x+y

当我使用 PairRDDFunctions.reduceByKey 时, reduceByKey((x, y) => x + y, 4) 可以工作。我真的不明白它有什么不同?

最佳答案

发生这种情况是因为 PairRDDFunctions 方法只有一个 def 重载reduceByKey(func: (V, V) ⇒ V, [SOMETHING])PairDStreamFunctions 有两个:

def reduceByKey(reduceFunc: (V, V) ⇒ V, numPartitions: Int)
def reduceByKey(reduceFunc: (V, V) ⇒ V, partitioner: Partitioner)

因此,尽管 partitioner 变体应该被排除作为一种可能性,但它仍然会出现并使编译器感到困惑。您可以通过显式命名来看到这一点:

.reduceByKey((x, y) => x + y,partitioner = 4)

我不确定这在编译器定义中的位置,但它清楚地表明了上述原因。

关于scala - 为什么当我编写 PairDStreamFunctions.reduceByKey 时 scala 编译器无法推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49103223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com