Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Generic function references [duplicate]

Tags:

kotlin

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")
like image 349
Matthew Layton Avatar asked Sep 16 '25 02:09

Matthew Layton


1 Answers

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.

like image 190
SpencerPark Avatar answered Sep 18 '25 16:09

SpencerPark