[英]Scala Generics with trait implementation -
I want to build a messaging Queue Consumer, which for now will have only one implementation for Kafka but later on, it can have other implementations as well. 我想构建一个消息传递队列使用者,它目前仅对Kafka具有一个实现,但以后也可以具有其他实现。
trait MessagingQueueConsumer {
def consume[B <: NotificationConsumerRecords](topic: String, userNames: List[String]): TrieMap[String, B]
}
Here NotificationConsumerRecords is an abstract class for the records I consume from the messaging queue. 在这里,NotificationConsumerRecords是我从消息传递队列使用的记录的抽象类。
sealed abstract class NotificationConsumerRecords
and a case class extending it. 和扩展它的案例类。
case class KafkaConsumerRecords[K,V](records: List[ConsumerRecord[K,V]]) extends NotificationConsumerRecords
And consume method should be able to accept all subtypes of NotificationConsumerRecords, that's why there is consume[B <: NotificationConsumerRecords] 并且消耗方法应该能够接受NotificationConsumerRecords的所有子类型,这就是为什么存在消耗[B <:NotificationConsumerRecords]
Now, When I extend this trait for Kafka and try to implement consume 现在,当我为Kafka扩展此特征并尝试实现消耗时
class KafkaMessagingQueueConsumer extends MessagingQueueConsumer {
override def consume[KafkaConsumerRecords](topic: String, userNames: List[String]): TrieMap[String, KafkaConsumerRecords[String, String]] = {}
}
Or 要么
class KafkaMessagingQueueConsumer extends MessagingQueueConsumer {
override def consume[KafkaConsumerRecords[String, String]](topic: String, userNames: List[String]): TrieMap[String, KafkaConsumerRecords[String, String]] = {}
}
I get compile time error in both cases. 在这两种情况下,我都会遇到编译时错误。 and I guess I understand that the problem here is that compiler is taking them as some generic type instead of a particular type. 而且我想我知道这里的问题是编译器将它们作为某种通用类型而不是特定类型。
But I do not know what should I do to let the compiler know that this KafkaMessagingQueueConsumer should accept only KafkaConsumerRecords. 但是我不知道该怎么做才能让编译器知道该KafkaMessagingQueueConsumer应该只接受KafkaConsumerRecords。
You've added the type parameter to the method, but you want the parameter on the trait. 您已经将type参数添加到方法中,但是想要在trait上使用该参数。
Try this instead: 尝试以下方法:
// Consumer for "B".
trait MessagingQueueConsumer[B <: NotificationConsumerRecords] {
def consume(topic: String, userNames: List[String]): TrieMap[String, B]
}
And when implementing: 在实施时:
class KafkaMessagingQueueConsumer
extends MessagingQueueConsumer[KafkaConsumerRecords] {
override def consume(
topic: String,
userNames: List[String]
): TrieMap[String, KafkaConsumerRecords[String, String]] = {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.