简体   繁体   中英

Casting a Generic type to AnyRef in Scala

I have a problem regarding type safety in scala. In fact, in Java I could cast a generic type to an Object. The annotation @SuppressWarning("unchecked") did the job. However in scala I am struggling to find a way to do that. I have tried Shapeless API using Typeable class, didn't work either. Here's my code snippet :

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) => { value.get() }) //(1)
       //(1) --> 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
  }     
}

This is data.computeIfAbsent() signature : data.computeIfAbsent(x: String, y: Function[ _ >: String, _ <: AnyRef]): AnyRef . The function I am giving to data.computeIfAbsent() returns the generic type T . I am unable to cast T to AnyRef , that is why I am getting the error message above.

Are you looking for casting in Scala?

import java.util.HashMap
import java.util.function.Supplier

class MyClass {

  val data: HashMap[String, AnyRef] = new HashMap[String, AnyRef]()

  def foo[T <: AnyRef](key: String, value: Supplier[T]): T = synchronized {

    data.computeIfAbsent(key, (s: String) => value.get()).asInstanceOf[T] 
  }
}

I'd suggest avoiding this specific problem by using HashMap[String, Any] , but to cast to AnyRef you just write value.get().asInstanceOf[AnyRef] . Of course,

data.computeIfAbsent(key, (s: String) => { value.get().asInstanceOf[AnyRef] })

will return AnyRef , not T . You can fix this with

data.computeIfAbsent(key, (s: String) => { value.get().asInstanceOf[AnyRef] }).asInstanceOf[T]

and it should be safe, but the compiler wouldn't help you spot the mistake if it weren't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM