'Implementing MongoDB CodecProvider with Kotlin giving Type mismatch Compilation Error
I am trying to implement MongoDB CodecProvider interface using Kotlin.
The interface only has the following method (in Java)
<T> Codec<T> get(Class<T> clazz, CodecRegistry registry);
when I try to implement this with Kotlin.
For example using IntegerCodec (which implements Codec<Integer> in the mongoDB Java driver):
override fun <T : Any?> get(clazz: Class<T>?, registry: CodecRegistry?): Codec<T> {
return IntegerCodec()
}
The Kotlin compiler gives me an error saying:
Type mismatch: inferred type is IntegerCodec but Codec<T> was expected
I do not understand why Kotlin is complaining about this. Is there any special handling we have to do to implement generic Java interface with Kotlin?
Solution 1:[1]
As the overridden method signature is still generic, you need to cast the return value
return IntegerCodec() as Codec<T>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sidgate |
