如何摆脱:类型需要但T找到

时间:2014-10-25 21:22:41

标签: scala

如何解决此编译错误:

trait Container {
  def getInts() : Seq[Int]
  def getStrings() : Seq[String]

  def put[T](t: T)
  def get[T] : Seq[T]
}

class MutableContainer extends Container {
  val entities = new mutable.HashMap[Class[_], mutable.Set[Any]]() with mutable.MultiMap[Class[_], Any]

  override def getStrings(): Seq[String] = entities.get(classOf[String]).map(_.toSeq).getOrElse(Seq.empty).asInstanceOf[Seq[String]] //strings
  override def getInts(): Seq[Int] = entities.get(classOf[Int]).map(_.toSeq).getOrElse(Seq.empty).asInstanceOf[Seq[Int]]

  override def get[T]: Seq[T] = entities.get(classOf[T]).map(_.toSeq).getOrElse(Seq.empty).asInstanceOf[Seq[T]]
  override def put[T](t: T): Unit = entities.addBinding(t.getClass, t)
}

这是错误:

[error] Container.scala:23: class type required but T found
[error]       override def get[T]: Seq[T] = entities.get(classOf[T]).map(_.toSeq).getOrElse(Seq.empty).asInstanceOf[Seq[T]]

2 个答案:

答案 0 :(得分:27)

T不是类类型,而是类型参数。申请ClassTag

import scala.reflect._

override def get[T](implicit ct: ClassTag[T]): Seq[T] =
  entities.get(ct.runtimeClass)
          .map(_.toSeq)
          .getOrElse(Seq.empty)
          .asInstanceOf[Seq[T]]

但这带来了另一个问题;这不是一个覆盖!

所以你必须修改基类来声明get,如下所示:

def get[T: ClassTag]: Seq[T]

答案 1 :(得分:2)

没有反射的解决方案

trait Container {
  def getInts() : Seq[Int]
  def getStrings() : Seq[String]
  def put[T](clazz: Class[T],t :T)
  def get[T](clazz: Class[T]) : Seq[T]
}

class MutableContainer extends Container {
  val entities = new mutable.HashMap[Class[_], mutable.Set[Any]]() with mutable.MultiMap[Class[_],Any]
  override def getStrings(): Seq[String] = entities.get(classOf[String]).map(_.toSeq).getOrElse(Seq.empty).asInstanceOf[Seq[String]] //strings
  override def getInts(): Seq[Int] = entities.get(classOf[Int]).map(_.toSeq).getOrElse(Seq.empty).asInstanceOf[Seq[Int]]
  override def get[T](clazz: Class[T]): Seq[T] = entities.get(clazz).map(_.toSeq).getOrElse(Seq.empty).asInstanceOf[Seq[T]]
  override def put[T](clazz: Class[T],t :T): Unit = entities.addBinding(clazz, t)
}