Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin warning: accessing non-final property in constructor

Tags:

kotlin

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?

like image 219
ttt Avatar asked Oct 28 '25 07:10

ttt


1 Answers

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.

like image 81
DAA Avatar answered Oct 31 '25 00:10

DAA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!