title: Kotlin generic factory dynamic cast
body: <p>I want to create factory of objects with generic parameter:</p>
  
  <pre><code>interface Foo&lt;T&gt; {
      fun buzz(param: T)
  }
  </code></pre>
  
  <p>I have two implementations for tests:</p>
  
  <pre><code>class FooImpl1 : Foo&lt;String&gt; {
      override fun buzz(param: String) {
          // implementation 1
      }
  }
  
  class FooImpl2 : Foo&lt;Int&gt; {
      override fun buzz(param: Int) {
          // implementation 2
      }
  }
  </code></pre>
  
  <p>Now I have created map to contain all my implementations </p>
  
  <pre><code>val implementationMap = mapOf&lt;String, Foo&lt;*&gt;&gt;(
      Pair(firstKey, FooImpl1()),
      Pair(secKey, FooImpl2())
  )
  </code></pre>
  
  <p>also I have map with params:</p>
  
  <pre><code>val paramMap = mapOf&lt;String, Any&gt;(
      Pair(firstKey, "String param"),
      Pair(secKey, 12)
  )
  </code></pre>
  
  <p>but now when I fetch first element from my map:</p>
  
  <pre><code>implementationMap.getValue(firstKey).buzz(paramMap.getValue(firstKey))
  </code></pre>
  
  <p>my <code>buzz</code> method rejects any param (wants <code>Nothing</code> as type)</p>
  
  <p>So I have created another map with types</p>
  
  <pre><code>val classMap = mapOf&lt;String, KClass&lt;*&gt;&gt;(
      Pair(firstKey, FooImpl1::class),
      Pair(secKey, FooImpl2::class)
  )
  
  val paramClassMap = mapOf&lt;String, KClass&lt;*&gt;&gt;(
      Pair(firstKey, String::class),
      Pair(secKey, Int::class)
  )
  </code></pre>
  
  <p>But I cannot cast it like that:</p>
  
  <pre><code>implementationMap.getValue(firstKey)
      .cast &lt; classMap.getValue(firstKey) &gt; () // not possible
      .buzz(
          paramMap.getValue(firstKey)
          .cast &lt; paramClassMap.getValue(firstKey) &gt; () // not possible
      )
  </code></pre>
  
  <p>or that</p>
  
  <pre><code>(implementationMap.getValue(firstKey) // FooImpl1
      /*not possible */ as classMap.getValue(firstKey)) // (FooImpl1::class)
      .buzz(
          paramMap.getValue(firstKey) // String
          /*not possible */ as paramClassMap.getValue(firstKey)) // (String::class)
  </code></pre>
  
  <p>I also tried to use <code>Token</code> type but it does not help eather:</p>
  
  <pre><code>val classMap = mapOf&lt;String, Type&gt;(
      Pair(firstKey, object: TypeToken&lt;FooImpl1&gt;() {}.type),
      Pair(secKey, object: TypeToken&lt;FooImpl1&gt;() {}.type)
  )
  </code></pre>
  
  <p>Any ideas how to cast it properly? Or some "different approach" ideas?</p>