duckertito duckertito - 1 month ago 13
Scala Question

Expression of type KafkaProducer[String,String] doesn't conform to expected type Null

I want to be able to initialize the variable

producer
from the function
setProducer
.

object MyObj {
var producer = null

def setProducer(p: KafkaProducer[String,String]): Unit = {
producer = p
}

//...
}


However it says that
Expression of type KafkaProducer[String,String] doesn't conform to expected type Null
.

So, how can I initialize
producer
?

Answer

You need to provide a type for the variable, for example:

object MyObj { 
  var producer: KafkaProducer[String,String] = null                                                                                                                  

  def setProducer(p: KafkaProducer[String,String]): Unit = {           
    producer = p                                                       
  }   

  //...
}