Hakon Grotte
11/01/2022, 11:21 AMclass ResourceProducer(
private val resourceAProducer: Producer<String, ResourceA>,
private val resourceBProducer: Producer<String, ResourceB>
) {
fun getCorrectKafkaProducer(resource: Resource): Producer<String, SpecificRecord> {
return when(someSealedClass) {
ValueA -> resourceAProducer <-- does not compile
ValueB -> resourceBProducer <-- does not compile
}
}
^-- Compiler error msg: Type mismatch: Required: Producer<String, SpecificRecord>, Found: Producer<String, ResourceA/B>
fun getSpecificRecord(resource: Resource): SpecificRecord {
return when(someSealedClass) {
ValueA -> ResourceA <-- this compiles
ValueB -> ResourceB <-- this compiles
}
}
}
Hakon Grotte
11/01/2022, 11:21 AMProducer
is a Java generic interface
public interface Producer<K, V> extends Closeable {... Future<RecordMetadata send(ProducerRecord<K, V record) ...}
.
SpecificRecord
is a Java interface public interface SpecificRecord extends IndexedRecord {}
.
ResourceA
and ResourceB
are auto-generated classed based on schema files, and they implement `SpecificRecord`:
public class ResourceA extends SpecificRecordBase implements SpecificRecord
public class ResourceB extends SpecificRecordBase implements SpecificRecord
SpecificRecordBase
is an abstract class.Sam
11/01/2022, 11:23 AMout
variance at the use site?
fun getCorrectKafkaProducer(resource: Resource): Producer<String, out SpecificRecord>
Sam
11/01/2022, 11:23 AMHakon Grotte
11/01/2022, 11:24 AMgetCorrectKafkaProducer
compile. The issue, however, is that then I cannot use the
Future<RecordMetadata send(ProducerRecord<K, V record)
method anymore (the compiler expects Nothing
as the record
type argument at that pointSam
11/01/2022, 11:27 AMV
was an output type for the producer (because of the class name) but it looks like it’s actually an input typeSam
11/01/2022, 11:30 AMProducer<String, ResourceB>
can’t be used as a Producer<String, SpecificRecord>
because that would imply that its send
method could accept any ProducerRecord<String, SpecificRecord>
, when it actually only accepts ProducerRecord<String, ResourceB>
.Sam
11/01/2022, 11:31 AMHakon Grotte
11/01/2022, 11:41 AM