在Scala的Spark RDD中使用Option和None

Rob*_*lds 2 scala apache-spark rdd

我有2个RDD [Int]源和noSourcesVertex。我想计算一个将创建2个新RDD的地图。

  val sourcesFormatted = sources.map(x => (Some(x), (Some(x), Some(x))))
  val noSourcesVertexFormatted = noSourcesVertex.map(x => (Some(x), (Some(x), None)))
  val outInit = sourcesFormatted.union(noSourcesVertexFormatted)
Run Code Online (Sandbox Code Playgroud)

但是当我执行先例代码时,出现错误:

错误:类型不匹配;找到:org.apache.spark.rdd.RDD [(Some [Int],(Some [Int],None.type))]]必需:org.apache.spark.rdd.RDD [(Some [Int],(Some [Int],Some [Int]))] val outInit = sourcesFormatted.union(noSourcesVertexFormatted)

我认为发生此错误是因为我试图加入其第三列具有不同类型的2个RDD。

由于我对Option的机制的理解,我没想到这种行为,Some(something)和None具有相同的类型-> Option。

为什么我会出现此错误?

小智 5

RDDs 是不变的,因此您必须具体说明类型:

val sourcesFormatted: RDD[(Option[Int] (Option[Int], Option[Int]))] = 
  sources.map(x => (Some(x), (Some(x), Some(x))))
val noSourcesVertexFormatted: RDD[(Option[Int] (Option[Int], Option[Int]))] = 
  noSourcesVertex.map(x => (Some(x), (Some(x), None)))
Run Code Online (Sandbox Code Playgroud)

要么

val noSourcesVertexFormatted = 
  noSourcesVertex.map(x => (Some(x), (Some(x), None: Option[Int])))
Run Code Online (Sandbox Code Playgroud)