I have some following code and got a warning for producer variable which is accessing non-final property in constructor
class KafkaService {
  val producer: KafkaProducer<String, String>
  init {
    val props = Properties()
    props[ProducerConfig.BOOTSTRAP_SERVERS_CONFIG] = "127.0.0.1:9092"
    props[ProducerConfig.CLIENT_ID_CONFIG] = "DemoProducer"
    props[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java.name
    props[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java.name
    producer = KafkaProducer(props)
  }
  fun sendToKafka(topic: String, message: String) {
    val producerRecord: ProducerRecord<String?, String> = ProducerRecord(topic, null, message)
    producer.send(producerRecord)
  }
}
What's the best way to fix this?
You should initialize your producervariable as lazy:
class KafkaService {
  val producer: KafkaProducer<String, String> by lazy {
    val props = Properties()
    props[ProducerConfig.BOOTSTRAP_SERVERS_CONFIG] = "127.0.0.1:9092"
    props[ProducerConfig.CLIENT_ID_CONFIG] = "DemoProducer"
    props[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java.name
    props[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java.name
    KafkaProducer(props)
  }
  fun sendToKafka(topic: String, message: String) {
    val producerRecord: ProducerRecord<String?, String> = ProducerRecord(topic, null, message)
    producer.send(producerRecord)
  }
}
This way, your variable will be initialized the first time you access it, and you won't be reassigning a final variable. Give this a read for a better understanding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With