简体   繁体   中英

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

在此处输入图像描述

You do not need a diamond operator in your code. Change the error line to this

KafkaConsumer consumer = new KafkaConsumer(props);

The return type should change from Consumer<Long, String> to KafkaConsumer . Rest all code is fine and you can use the consumer as it is.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM