In kotlin, how to return an instance defined by generic class parameter
<p>I'm trying to write a nice Kotlin wrapper for a web framework against kotlin 1.0.3. In that I am trying to mixin a function to the request to have it return a bean via a JSON transformation using jackson.</p>

<p>So in my library I have the following</p>

<pre><code>private val mapper: ObjectMapper = ObjectMapper().registerModule(KotlinModule())
fun &lt;T : Any&gt; Request.asDataBean(type: KClass&lt;T&gt;): T = mapper.readValue(this.body(), type.java)
</code></pre>

<p>But when I goto use the code as such</p>

<pre><code>post("/hello", { req, res -&gt;
    val bean = req.asDataBean(TestBean::class)
})
</code></pre>

<p>It errors saying that the expected value of bean is Any. What I want is for my API to work as above where whatever the generic "class" definition that is passed into asDataBean method is the type of value that is returned back.</p>

<p>I've also tried </p>

<pre><code>fun &lt;T&gt; Request.asDataBean(type: KClass&lt;*&gt;): T = mapper.readValue(this.body(), type.java) as T
</code></pre>

<p>as well as changing the usage code to </p>

<pre><code>val bean: TestBean = req.asDataBean(TestBean::class)
</code></pre>

<p>in hopes of making it work but they also give the exact same error when using the code.</p>

<p>How do I get it to use the generic defined by the class type passed in as the parameter (very similar to how all the spring api's work in java)?</p>