I'm trying to do a Kafka tutorial in Kotlin and wo...
# getting-started
w
I'm trying to do a Kafka tutorial in Kotlin and wondered what the following code is in idiomatic Kotlin
Copy code
// send data - asynchronous
            producer.send(record, new Callback() {
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    // executes every time a record is successfully sent or an exception is thrown
                    if (e == null) {
                        // the record was successfully sent
                        <http://logger.info|logger.info>("Received new metadata. \n" +
                                "Topic:" + recordMetadata.topic() + "\n" +
                                "Partition: " + recordMetadata.partition() + "\n" +
                                "Offset: " + recordMetadata.offset() + "\n" +
                                "Timestamp: " + recordMetadata.timestamp());
                    } else {
                        logger.error("Error while producing", e);
                    }
                }
            });
        }
Copy/pasting this code into IntelliJ and letting it do the Kotlin conversion yields something that is broken.
It has been long since I did any Java but it looks like Callback is being extended with an implementation of onCompletion() i.e. anonymous class?
Would it make sense to use an extension function on Callback here?
fun Callback.onCompletion(recordMetadata: RecordMetadata, e: Exception) { ... }
a
Copy code
// send data - asynchronous
    producer.send(record, object: Callback() {
        fun onCompletion(recordMetadata: RecordMetadata, e: Exception?) {
            // executes every time a record is successfully sent or an exception is thrown
            if (e == null) {
                // the record was successfully sent
                <http://logger.info|logger.info>("Received new metadata. \n" +
                        "Topic:" + recordMetadata.topic() + "\n" +
                        "Partition: " + recordMetadata.partition() + "\n" +
                        "Offset: " + recordMetadata.offset() + "\n" +
                        "Timestamp: " + recordMetadata.timestamp())
            } else {
                logger.error("Error while producing", e)
            }
        }
    })
i believe that should be valid and does the same as the java version with creating an anonymous class (might need an override on the
fun onCompletion
)
w
I see you used the object keyword above
ok, that creates an anonymous inner class
I'll try this out
Seems to work! Thanks @akatkov. My next step was to try the nested class / object keyword.
👍 1
You beat me to it 🙂