试图理解'申请'方法。我想创建一个类,它返回List,Array或Set,具体取决于传递的参数。该代码适用于List和Set,但不适用于Array。我无法理解这个问题
class CollectionFactory [A](s:String){}
object CollectionFactory {
def apply[A](s: String): Traversable[A] = {
s match {
case "list" => {
List[A]()
}
//this doesnt work. It seems using [A] is incorrect. How do I specify the type?
/*
case "array" => {
new Array[A](1)
}
*/
case _ => {
Set[A]() }
}
}
}
val c = CollectionFactory[Int]("list")
c: Traversable[Int] = List()
CollectionFactory[String]("list")
res0: Traversable[String] = List()
CollectionFactory[Boolean]("")
res1: Traversable[Boolean] = Set()
答案 0 :(得分:0)
您需要ClassTag[A]
来实例化新的Array[A]
。通过添加implicit ct: ClassTag[A]
参数可以轻松解决此问题。
object CollectionFactory {
def apply[A: reflect.ClassTag](s: String): Traversable[A] = {
s match {
case "list" => List[A]()
case "array" => new Array[A](1)
case _ => Set[A]()
}
}
}