Is there a way to have a function return a functio...
# getting-started
k
Is there a way to have a function return a function with a generic type in Kotlin? I want to do
Copy code
fun doSomething(): (Class<T>) -> T {}
However because lambda expressions can't have generic types, this doesn't compile for me.
e
Copy code
fun <T> doSomething(): (Class<T>) -> T
would be legal
k
True, however I don't want to make
doSomething
generic.
😕 1
e
"(Class<T>) -> T for all possible T" is not a denotable type
k
I think I'm going to have to decompose the problem differently
e
Copy code
fun interface DoSomething<T> : (Class<T>) -> T
fun doSomething(): DoSomething<*> {}
is also legal, but pretty awkward (it's not the lambda type itself, it's a subtype)
that sort of wrapper is still a reasonable solution in some cases - e.g. how kotlin.coroutines.CoroutineContext/.Element/.Key is parameterized, or https://github.com/brutall/typedmap - but you do need something else to maintain the constraint
r
If you're okay with a separate interface, why not ``````
Copy code
interface I {
    operator fun <T> invoke(klazz: Class<T>): T
}
k
@randomcat Thanks for the suggestion. I also got some help from the #arrow channel and got the same suggestion. I updated my code yesterday (AEST) to use this and it works perfectly.
r
ah, glad you figured it out
👍 1