title: Casting a Generic type to AnyRef in Scala
body: <p>I have a problem regarding type safety in scala. In fact, in Java I could cast a generic type to an Object. The annotation <code>@SuppressWarning("unchecked")</code> did the job. However in scala I am struggling to find a way to do that. I have tried <code>Shapeless</code> API using <code>Typeable</code> class, didn't work either. Here's my code snippet :</p>
  
  <pre><code>class MyClass {
     val data: HashMap[String, AnyRef] = new HashMap[String, AnyRef]();
  
    def foo[T](key: String, value: Supplier[T]): T = synchronized {
  
         data.computeIfAbsent(key, (s: String) =&gt; { value.get() }) //(1)
         //(1) --&gt; The compiler says : type mismatch; found : T required: AnyRef Note that T is unbounded, which means AnyRef is not a known parent.
         // Such types can participate in value classes, but instances cannot appear in singleton types or in reference comparisons
    }     
  }
  </code></pre>
  
  <p>This is <code>data.computeIfAbsent()</code> signature : <code>data.computeIfAbsent(x: String, y: Function[ _ &gt;: String, _ &lt;: AnyRef]): AnyRef</code>. The function I am giving to <code>data.computeIfAbsent()</code> returns the generic type <code>T</code>. I am unable to cast <code>T</code> to <code>AnyRef</code>, that is why I am getting the error message above. </p>