title: Kotlin: Generic function as return type?
body: <p>In Kotlin, is it possible to declare a generic function type as the return type of a function?</p>
  
  <p>What I want to achieve would look like this in Java:</p>
  
  <pre class="lang-java prettyprint-override"><code>interface Factory {
  
      static Factory INSTANCE = new FactoryImpl();
  
      &lt;T&gt; T create(String name, Class&lt;T&gt; type);
  
  }
  
  class PrefixedFactory implements Factory {
      private final String prefix;
  
      PrefixedFactory(String prefix) {
          this.prefix = prefix;
      }
  
      @Override
      public &lt;T&gt; T create(String name, Class&lt;T&gt; type) {
          return Factory.INSTANCE.create(prefix + name, type);
      }
  }
  </code></pre>
  
  <p>(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:</p>
  
  
  
  <pre><code>fun prefixer(prefix: String): &lt;T&gt; (String, KClass&lt;T&gt;) -&gt; T { TODO() }
  </code></pre>
  
  <p>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?</p>
  
  <h2>(Edit) Clarification</h2>
  
  <p>I want the actual result function to be generic. If I do</p>
  
  <pre><code>fun &lt;T: Any&gt; prefixer(prefix: String): (String, KClass&lt;T&gt;) -&gt; T { TODO() }
  </code></pre>
  
  <p>as the current answers suggest; I don't get a generic function, instead I get <code>(String, KClass&lt;Foo&gt;) -&gt; Foo</code> if I call <code>prefixer&lt;Foo&gt;("")</code>. So that function can only be called with <code>Foo</code>, while the factory function <code>prefixer</code> in that case is generic, the result is not. I hope that clears up the misunderstandings.</p>
  
  <p>My use case is in a Gradle plugin, where I wrote a helper method similar to this one that applies some defaults to each task created:</p>
  
  <pre><code>val myPrefix = "..."
  val project: Project = &lt;from context&gt;
  fun &lt;T: Task&gt; String.task(type: KClass&lt;T&gt;, doConfig: T.() -&gt; Unit) {
    project.tasks.create("$prefix$this", type.java, { it.doConfig() })
  }
  </code></pre>
  
  <p>Note that the project comes in as closure. Now I want to reuse that helper in a different plugin, so I would like to create this function using a factory for different project instances.</p>