Search code examples
javaspringgenericsapache-kafkaspring-kafka

Kafka Consumer diamond operator cannot infer arguments


I am creating a Kafka consumer. Mentioned piece of code is running fine on my sample POC project.

Somehow when I use this in my project application, it gives error, of not able to resolve Diamond Operator.

Project Code

private Consumer<Long, String> createConsumer(String topicName) {
    final Properties props = new Properties();
    // todo: use @Value instead of hardcodes
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "application");
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

    final Consumer<Long, String> consumer = new KafkaConsumer<>(props);
    consumer.subscribe(Collections.singletonList(topicName));
    return consumer;
}

Error Snapshot

enter image description here


Solution

  • This is reproducible as long as you import java.util.function.Consumer (having one generic type) which is not an interface that KafkaConsumer implements. You need to import the correct one:

    org.apache.kafka.clients.consumer.Consumer
    

    This one has two generic types and it should work with no compilation errors.

    final Consumer<Long, String> consumer = new KafkaConsumer<>(props);