首页 > 解决方案 > 具有相同签名和参数类型的 Scala 模糊引用

问题描述

Scala 如何显示一个模棱两可的引用错误,而这两种选择都具有相同的签名?如何克服它?

代码:

import org.apache.kafka.streams.test

val stringSerializer = new StringSerializer
val stringFactory: ConsumerRecordFactory[String, String] =
    new ConsumerRecordFactory[String, String](
      eventTopic, stringSerializer, stringSerializer)
val testKey : String = ""
val testVal : String = ""
val recordString : ConsumerRecord[Array[Byte], Array[Byte]] = 
    stringFactory.create(testKey, testVal)

ambiguous reference to overloaded definition,
[error] both method create in class ConsumerRecordFactory of type (x$1: String, x$2: String)org.apache.kafka.clients.consumer.ConsumerRecord[Array[Byte],Array[Byte]]
[error] and  method create in class ConsumerRecordFactory of type (x$1: String, x$2: String)org.apache.kafka.clients.consumer.ConsumerRecord[Array[Byte],Array[Byte]]
[error] match argument types (String,String) and expected result type org.apache.kafka.clients.consumer.ConsumerRecord[Array[Byte],Array[Byte]]
[error]     val recordString : ConsumerRecord[Array[Byte], Array[Byte]] = stringFactory.create(testKey, testVal)

如您所见,这两种方法具有相同的签名。使用其他类型的 CustomerFactory 时不会发生这种情况,即我有自定义序列化程序的自定义案例类类型(而不是提供的 StringSerializer)。

标签: scalaapache-kafkaapache-kafka-streamsscala-java-interop

解决方案


为了解决模棱两可的方法问题,您应该遵循以下方法。

  1. 使用 KeySerializer 和 ValueSerializer 创建 ConsumerRecordFactory 的实例

  2. 在 ConsumerRecord 中传递主题,后跟 Key 和 value。

例子 :

val stringSerializer = new StringSerializer
val stringFactory: ConsumerRecordFactory[String, String] =
    new ConsumerRecordFactory[String, String](
      stringSerializer, stringSerializer)
val testKey : String = ""
val testVal : String = ""
val recordString : ConsumerRecord[Array[Byte], Array[Byte]] = 
    stringFactory.create(eventTopic, testKey, testVal)

另一种选择是将键和值作为字节数组传递。

val stringFactory: ConsumerRecordFactory[String, String] =
    new ConsumerRecordFactory[String, String](
      eventTopic, stringSerializer, stringSerializer)
val testKey : String = ""
val testVal : String = ""
val recordString : ConsumerRecord[Array[Byte], Array[Byte]] = 
    stringFactory.create(testKey.getBytes, testVal.getBytes)

推荐阅读