[FIXED] Scala initialise sc.parallelise inside "if block" and execute outside loop

Issue

I've a following code :-

case class event(id: String, date: String)

object test {
  def main(args: Array[String]) {
  var collection = null
  if(some_condition){
     val a = some_value
     val b = value2
     val value3 = some_function_calculation_from other_class
     val c = value3
     val d = value4
    collection = sc.parallelize(Seq(event(a,b),event(c,d)))
  } else {
    collection = sc.parallelize(Seq(event(e,f),event(g,h)))
  }
  collection.saveToCassandra("db", "table", SomeColumns("id", "date"))
  }
}

I want to have my collection object to be saved in cassandra with values seq of event(a,b) & event(c,d) and when if condition fails it should be event(e,f) & event(g,h) but it is going as null. Where I'm going wrong ?

Note: It works fine when there is no if block that means all collection definition initialisation in one scope.

Thanks,


Solution

If you want collection as RDD[event] as per the condition then you could assign if else to a variable collection.

val collection = if (some_condition)
    sc.parallelize(Seq(event("a", "b"), event("c", "d")))
  else
    sc.parallelize(Seq(event("e", "f"), event("g", "h")))

Hope this helps!



Answered By - koiralo
Answer Checked By - Terry (sql.easybugfix Volunteer)

Related Posts

Post a Comment