I have an enum which is defined in Java and has th...
# getting-started
t
I have an enum which is defined in Java and has the property name, which is a string. now when I try to fetch this I get an Overload resolution ambiguity error, because Kotlin itself -also- defines name as a String, how do I access .name from the original enum class now? (Without using reflections)
p
did you try using
.getName
? or is it a public field?
t
It’s a public field
p
That’s a tricky one then. It converts
getName
(from
Enumeration
) into the property
name
. Only thing I can think of id to rename the original (if you have access to the source), or add an extra getter to access it from Kotlin so you don’t have to refactor the whole java code to the new name
Or do an extension function that uses reflexion, but that’s ugly as hell 😅
t
The code is from a Kafka library
p
Got a link to the enum in question?
p
ah, I think I found a solution… one sec
Could do this:
Copy code
private val compressionTypeNameField by lazy { CompressionType::name.javaField!! }
val CompressionType.compressionName 
    get() = compressionTypeNameField.get(this)
Uses reflexion, but should do the trick
t
Thanks! so basically reflection is the only way
p
AFAIK
t
Oh according to my colleague this doesn’t work either 😂
p
really? 🤔 ah! may need to get the declared field instead
t
But we have a working solution eitherway, i’ll post it in a second
p
CompressionType::class.java.getDeclaredField("name")
t
Jep pretty much, afaik
p
Yeah, the other will match the backing field of the property 😅
t
CompressionType::class.java.getField("name").get(CompressionType.ZSTD)
p
Or
Copy code
private val compressionTypeNameField by lazy { CompressionType::class.java.getField("name")!! }
val CompressionType.compressionName 
    get() = compressionTypeNameField.get(this)
as before 🙂 Reusable and it means it only uses reflexion look up once too
i
👍 1