title: Spark NullPointerException inside foreach loop
body: <p>I have RDD and I want to loop over it. I do like this:</p>
  
  <pre><code>pointsMap.foreach({ p =&gt;
    val pointsWithCoordinatesWithDistance = pointsMap.leftOuterJoin(xCoordinatesWithDistance)
    pointsWithCoordinatesWithDistance.foreach(println)
    println("---")
  })
  </code></pre>
  
  <p>However, NullPointerException is occuring:</p>
  
  <pre><code>java.lang.NullPointerException
      at org.apache.spark.rdd.RDD.&lt;init&gt;(RDD.scala:125)
      at org.apache.spark.rdd.CoGroupedRDD.&lt;init&gt;(CoGroupedRDD.scala:69)
      at org.apache.spark.rdd.PairRDDFunctions.cogroup(PairRDDFunctions.scala:651)
      at org.apache.spark.rdd.PairRDDFunctions.leftOuterJoin(PairRDDFunctions.scala:483)
      at org.apache.spark.rdd.PairRDDFunctions.leftOuterJoin(PairRDDFunctions.scala:555)
  ...
  </code></pre>
  
  <p>Both <code>pointsMap</code> and <code>xCoordinatesWithDistance</code> are initialized before foreach and contain elements. Not inside foreach loop <code>leftOuterJoin</code> also works. For the full version of my code please see <a href="https://github.com/timasjov/spark-learning/blob/master/src/DBSCAN.scala" rel="nofollow">https://github.com/timasjov/spark-learning/blob/master/src/DBSCAN.scala</a></p>