0
嘗試理解「應用」方法。我想創建一個類,根據傳遞的參數返回一個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()
#1不是一個問題:它會被隱式轉換成'WrappedArray',這_is_一個'Traversable' – Dima
@Dima好一點。 –