https://kotlinlang.org logo
#codereview
Title
# codereview
t

tianhao

07/25/2018, 6:01 AM
Hi, guys below is my code to send a message to Kafka using Java API, I would like to do a code review and meanwhile for producer value a got a warning like
accessing non-final property in constructor
not sure how is the fix for that? Thanks
Copy code
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)
  }
}
h

hho

07/25/2018, 1:09 PM
That warning seems wrong to me – producer is a
val
and you're only accessing it in the constructor to initialize it. The only thing I would change in this code snippet is to make producer
private
.
2 Views