Given the following class
class Foo {
fun bar() {}
}
I can reference the bar
function like so
Foo::bar
I want to be able to do this for generic functions
class Foo {
fun <T> bar() {}
}
But the compiler throws the following error
Kotlin: Type inference failed: Not enough information to infer parameter T in fun bar(): Unit Please specify it explicitly.
How can I provide the parameter for generic function references?
Workaround 1 (Function proxy)
Proxy is probably the wrong term here but until someone tells me otherwise...
One approach I've been able to do is proxy the function, removing the generic type, but this isn't a great approach if I'm honest...
fun Foo.barOfInt() = bar<Int>()
Which can be referenced normally...
Foo::barOfInt
Workaround 2 (Get by name)
The second approach that seems successful, albeit still not very clean would be to build a KClass<*>
extension that can get the method by name...
fun KClass<*>.getGenericFunction(name: String): KFunction<*> {
return members.single { it.name == name } as KFunction<*>
}
Which I can use like so...
Foo::class.getGenericFunction("bar")
In your example T
is a phantom type (not used anywhere) so there is nothing for the type inference to latch onto and it must therefore be declared explicitly. Unfortunately as mentioned in References to generic functions, KT-12140 is still open and there is no syntax for such a declaration with the point free method reference notation.
Creating the lambda fun (foo: Foo) = foo.bar<Int>()
looks like your best bet currently although simply using the type T
somewhere else in the signature would likely give the type inference enough to go off of such that this wouldn't be necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With