【问题标题】:Type mismatch, found SortedSet, required Any类型不匹配,找到 SortedSet,需要 Any
【发布时间】:2019-08-22 05:51:19
【问题描述】:

使用combinebyKey时,出现如下类型不匹配错误

scala> rdd.map(x => (x._1, x._2))
          .combineByKey( (x: Int) => x, 
                         (acc: SortedSet[Int], x: Int) => (acc += x), 
                         (acc1: SortedSet[Int], acc2: SortedSet[Int]) => (acc1 ++= acc2))

<console>:29: error: type mismatch;
 found   : (scala.collection.mutable.SortedSet[Int], Int) => scala.collection.mutable.SortedSet[Int]
 required: (Any, Int) => Any
       rdd.map(x => (x._1, x._2)).combineByKey( (x: Int) => x, (acc: SortedSet[Int], x: Int) => (acc += x), (acc1: SortedSet[Int], acc2: SortedSet[Int]) => (acc1 ++= acc2))
                                                                                             ^
<console>:29: error: type mismatch;
 found   : (scala.collection.mutable.SortedSet[Int], scala.collection.mutable.SortedSet[Int]) => scala.collection.mutable.SortedSet[Int]
 required: (Any, Any) => Any
       rdd.map(x => (x._1, x._2)).combineByKey( (x: Int) => x, (acc: SortedSet[Int], x: Int) => (acc += x), (acc1: SortedSet[Int], acc2: SortedSet[Int]) => (acc1 ++= acc2))

为什么 scala 不能将 scala.collection.mutable.SortedSet[Int] 视为 Any

这是我试过的代码:

import scala.collection.mutable.SortedSet
val data = Array((1, 1, 1), 
                 (1, 1, 2),
                 (1, 1, 3),
                 (1, 2, 1),
                 (1, 2, 2),
                 (1, 2, 3), 
                 (2, 1, 1), 
                 (2, 1, 2), 
                 (2, 1, 3), 
                 (2, 2, 1), 
                 (2, 2, 2), 
                 (2, 2, 3))
val rdd = sc.parallelize(data)

rdd.map(x => (x._1, x._2))
   .combineByKey( (x: Int) => x, 
                  (acc: SortedSet[Int], x: Int) => (acc += x), 
(acc1: SortedSet[Int], acc2: SortedSet[Int]) => (acc1 ++= acc2))

我希望得到 ((1, (1,2)), (2, (1,2)),键/值对中哪个值不包含重复元素。

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    第一个函数的返回类型需要是有序集合,spark需要知道如何构造combiners。像这样的东西应该可以工作

    rdd.map(x => (x._1, x._2)).combineByKey( 
      (x: Int) => new mutable.TreeSet[Int] += x, 
      (acc: SortedSet[Int], x: Int) => (acc += x), 
      (acc1: SortedSet[Int], acc2: SortedSet[Int]) => (acc1 ++= acc2))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-26
      • 2019-04-30
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 2018-12-13
      相关资源
      最近更新 更多