title: Getting Exception when Safe-Casting to Generic Type in Kotlin
body: <p>I am using safe casting option in kotlin i.e. <code>as?</code> still i am getting class cast exception when the data types are not compatible, this is happening when I am doing this via a generic method written to perform case, however if I directly perform the cast it returns null as expected from a safe cast</p>
  <pre><code>class CastTest(val data: Any) {
  
     fun castViaGenericMethod(): TypeA? {
        return castToContext&lt;TypeA&gt;()
     }
  
     fun castDirectly(): TypeA? {
        return data as? TypeA
     }
  
     private fun &lt;CONTEXT&gt; castToContext(): CONTEXT? = data as? CONTEXT
  
  }
  </code></pre>
  <p><code>castViaGenericMethod()</code> -&gt; this method throws <code>ClassCastException</code> when the data is not of the type <code>TypeA</code>.
  <code>castDirectly()</code> -&gt; this returns <code>null</code> when the cast is not possible.</p>
  <p>Please suggest how can this be done.</p>