What’s the most idiomatic way to attach a reified ...
# codereview
a
What’s the most idiomatic way to attach a reified function to an interface? currently I’m adding an extension function next to the interface in the same file, but it’s not very discoverable: The user has to know about this and import it explicitly before use:
Copy code
interface IExample {
  fun <T> something(cls: KClass<T>)
}

inline fun <reified T> ITest.something() = something(T::class)
Copy code
val t: IExample = Example()
// caller has to manually know about, and import extension function before they can do
t.something<String>()
j
That's what I usually do as well. To be honest, this specific issue with discoverability is common enough across many libraries that I personally rely a lot on the tooling to give me all the overloads (I always use
Ctrl+Space
to autocomplete members in IJ and it finds and auto-imports extensions when needed), so I don't consider this much of a problem anymore.
a
alright, thanks. I have (thought i had) noticed some times it isn’t discovered automatically but maybe i have just been impatient or some misconfiguration.
j
I haven't faced those in a while, but maybe it's just my memory playing games 😄
k
The way you've done it is exactly how Jackson defines its Kotlin extensions:
Copy code
inline fun <reified T> ObjectMapper.readValue(content: String): T = readValue(content, jacksonTypeRef<T>())
And indeed, whenever I try to use the
readValue
extension, I have trouble getting IntelliJ IDEA to recognize it until I manually import
com.fasterxml.jackson.module.kotlin.readValue
.
j
@Klitos Kyriacou did you try Ctrl+Space for completing these functions? It consistently works for me, I just have to pick the reified extension from the list instead of the regular member. (Don't get me wrong, I'm not saying it's perfect, but I got used to working like that and it doesn't feel too much of a hassle for me)
k
Ah, yes indeed it does. I thought Ctrl+Space only listed the member function variants, but in fact it does list the extension functions, but only at the bottom of a very long list that requires scrolling down twice, so I didn't see them. Thanks for pointing this out, as it is definitely a better experience than having to import manually.
l
@arve Completion is very broken when using K2, so if you're using that, you may want to switch back to K1 until they fixed it.