Functions with generic return type


#1

In Kotlin, is it possible to declare a generic function type as the return type of a function?

What I want to achieve would look like this in Java:

interface Factory {

static Factory INSTANCE = new FactoryImpl();

<T> T create(String name, Class<T> type);

}

class PrefixedFactory implements Factory {
private final String prefix;

PrefixedFactory(String prefix) {
    this.prefix = prefix;
}

@Override
public <T> T create(String name, Class<T> type) {
    return Factory.INSTANCE.create(prefix + name, type);
}

}

(Note that in the example I access the Factory instance using the static field to avoid passing a generic function as a parameter, which would present its own problems in Kotlin). I would like convert the prefixer to a kotlin function, but it seems to be impossible to declare a generic function as the return type:

fun prefixer(prefix: String): (String, KClass) -> T { TODO() }

This of course does not compile. It seems to me that this is a limitation compared to Java’s functional interfaces. Is there a way to accomplish this, or a workaround?


[Coroutines] resumeWithException not working as expected with custom continuation
#2

This compiles:

fun <T : Any> prefixer(prefix: String): (String, KClass<T>) -> T {
    TODO()
}