https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

kierans777

06/29/2021, 4:41 AM
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

ephemient

06/29/2021, 4:47 AM
Copy code
fun <T> doSomething(): (Class<T>) -> T
would be legal
k

kierans777

06/29/2021, 4:49 AM
True, however I don't want to make
doSomething
generic.
😕 1
e

ephemient

06/29/2021, 4:49 AM
"(Class<T>) -> T for all possible T" is not a denotable type
k

kierans777

06/29/2021, 4:50 AM
I think I'm going to have to decompose the problem differently
e

ephemient

06/29/2021, 4:50 AM
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

randomcat

06/30/2021, 12:16 AM
If you're okay with a separate interface, why not ``````
Copy code
interface I {
    operator fun <T> invoke(klazz: Class<T>): T
}
k

kierans777

06/30/2021, 12:47 AM
@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

randomcat

06/30/2021, 12:48 AM
ah, glad you figured it out
👍 1
3 Views